AwsClient.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <?php
  2. namespace Aws;
  3. use Aws\Api\ApiProvider;
  4. use Aws\Api\DocModel;
  5. use Aws\Api\Service;
  6. use Aws\Signature\SignatureProvider;
  7. use GuzzleHttp\Psr7\Uri;
  8. /**
  9. * Default AWS client implementation
  10. */
  11. class AwsClient implements AwsClientInterface
  12. {
  13. use AwsClientTrait;
  14. /** @var array */
  15. private $config;
  16. /** @var string */
  17. private $region;
  18. /** @var string */
  19. private $endpoint;
  20. /** @var Service */
  21. private $api;
  22. /** @var callable */
  23. private $signatureProvider;
  24. /** @var callable */
  25. private $credentialProvider;
  26. /** @var HandlerList */
  27. private $handlerList;
  28. /** @var array*/
  29. private $defaultRequestOptions;
  30. /**
  31. * Get an array of client constructor arguments used by the client.
  32. *
  33. * @return array
  34. */
  35. public static function getArguments()
  36. {
  37. return ClientResolver::getDefaultArguments();
  38. }
  39. /**
  40. * The client constructor accepts the following options:
  41. *
  42. * - api_provider: (callable) An optional PHP callable that accepts a
  43. * type, service, and version argument, and returns an array of
  44. * corresponding configuration data. The type value can be one of api,
  45. * waiter, or paginator.
  46. * - credentials:
  47. * (Aws\Credentials\CredentialsInterface|array|bool|callable) Specifies
  48. * the credentials used to sign requests. Provide an
  49. * Aws\Credentials\CredentialsInterface object, an associative array of
  50. * "key", "secret", and an optional "token" key, `false` to use null
  51. * credentials, or a callable credentials provider used to create
  52. * credentials or return null. See Aws\Credentials\CredentialProvider for
  53. * a list of built-in credentials providers. If no credentials are
  54. * provided, the SDK will attempt to load them from the environment.
  55. * - debug: (bool|array) Set to true to display debug information when
  56. * sending requests. Alternatively, you can provide an associative array
  57. * with the following keys: logfn: (callable) Function that is invoked
  58. * with log messages; stream_size: (int) When the size of a stream is
  59. * greater than this number, the stream data will not be logged (set to
  60. * "0" to not log any stream data); scrub_auth: (bool) Set to false to
  61. * disable the scrubbing of auth data from the logged messages; http:
  62. * (bool) Set to false to disable the "debug" feature of lower level HTTP
  63. * adapters (e.g., verbose curl output).
  64. * - stats: (bool|array) Set to true to gather transfer statistics on
  65. * requests sent. Alternatively, you can provide an associative array with
  66. * the following keys: retries: (bool) Set to false to disable reporting
  67. * on retries attempted; http: (bool) Set to true to enable collecting
  68. * statistics from lower level HTTP adapters (e.g., values returned in
  69. * GuzzleHttp\TransferStats). HTTP handlers must support an
  70. * `http_stats_receiver` option for this to have an effect; timer: (bool)
  71. * Set to true to enable a command timer that reports the total wall clock
  72. * time spent on an operation in seconds.
  73. * - endpoint: (string) The full URI of the webservice. This is only
  74. * required when connecting to a custom endpoint (e.g., a local version
  75. * of S3).
  76. * - endpoint_provider: (callable) An optional PHP callable that
  77. * accepts a hash of options including a "service" and "region" key and
  78. * returns NULL or a hash of endpoint data, of which the "endpoint" key
  79. * is required. See Aws\Endpoint\EndpointProvider for a list of built-in
  80. * providers.
  81. * - handler: (callable) A handler that accepts a command object,
  82. * request object and returns a promise that is fulfilled with an
  83. * Aws\ResultInterface object or rejected with an
  84. * Aws\Exception\AwsException. A handler does not accept a next handler
  85. * as it is terminal and expected to fulfill a command. If no handler is
  86. * provided, a default Guzzle handler will be utilized.
  87. * - http: (array, default=array(0)) Set to an array of SDK request
  88. * options to apply to each request (e.g., proxy, verify, etc.).
  89. * - http_handler: (callable) An HTTP handler is a function that
  90. * accepts a PSR-7 request object and returns a promise that is fulfilled
  91. * with a PSR-7 response object or rejected with an array of exception
  92. * data. NOTE: This option supersedes any provided "handler" option.
  93. * - idempotency_auto_fill: (bool|callable) Set to false to disable SDK to
  94. * populate parameters that enabled 'idempotencyToken' trait with a random
  95. * UUID v4 value on your behalf. Using default value 'true' still allows
  96. * parameter value to be overwritten when provided. Note: auto-fill only
  97. * works when cryptographically secure random bytes generator functions
  98. * (random_bytes, openssl_random_pseudo_bytes or mcrypt_create_iv) can be
  99. * found. You may also provide a callable source of random bytes.
  100. * - profile: (string) Allows you to specify which profile to use when
  101. * credentials are created from the AWS credentials file in your HOME
  102. * directory. This setting overrides the AWS_PROFILE environment
  103. * variable. Note: Specifying "profile" will cause the "credentials" key
  104. * to be ignored.
  105. * - region: (string, required) Region to connect to. See
  106. * http://docs.aws.amazon.com/general/latest/gr/rande.html for a list of
  107. * available regions.
  108. * - retries: (int, default=int(3)) Configures the maximum number of
  109. * allowed retries for a client (pass 0 to disable retries).
  110. * - scheme: (string, default=string(5) "https") URI scheme to use when
  111. * connecting connect. The SDK will utilize "https" endpoints (i.e.,
  112. * utilize SSL/TLS connections) by default. You can attempt to connect to
  113. * a service over an unencrypted "http" endpoint by setting ``scheme`` to
  114. * "http".
  115. * - signature_provider: (callable) A callable that accepts a signature
  116. * version name (e.g., "v4"), a service name, and region, and
  117. * returns a SignatureInterface object or null. This provider is used to
  118. * create signers utilized by the client. See
  119. * Aws\Signature\SignatureProvider for a list of built-in providers
  120. * - signature_version: (string) A string representing a custom
  121. * signature version to use with a service (e.g., v4). Note that
  122. * per/operation signature version MAY override this requested signature
  123. * version.
  124. * - validate: (bool, default=bool(true)) Set to false to disable
  125. * client-side parameter validation.
  126. * - version: (string, required) The version of the webservice to
  127. * utilize (e.g., 2006-03-01).
  128. *
  129. * @param array $args Client configuration arguments.
  130. *
  131. * @throws \InvalidArgumentException if any required options are missing or
  132. * the service is not supported.
  133. */
  134. public function __construct(array $args)
  135. {
  136. list($service, $exceptionClass) = $this->parseClass();
  137. if (!isset($args['service'])) {
  138. $args['service'] = manifest($service)['endpoint'];
  139. }
  140. if (!isset($args['exception_class'])) {
  141. $args['exception_class'] = $exceptionClass;
  142. }
  143. $this->handlerList = new HandlerList();
  144. $resolver = new ClientResolver(static::getArguments());
  145. $config = $resolver->resolve($args, $this->handlerList);
  146. $this->api = $config['api'];
  147. $this->signatureProvider = $config['signature_provider'];
  148. $this->endpoint = new Uri($config['endpoint']);
  149. $this->credentialProvider = $config['credentials'];
  150. $this->region = isset($config['region']) ? $config['region'] : null;
  151. $this->config = $config['config'];
  152. $this->defaultRequestOptions = $config['http'];
  153. $this->addSignatureMiddleware();
  154. $this->addInvocationId();
  155. if (isset($args['with_resolved'])) {
  156. $args['with_resolved']($config);
  157. }
  158. }
  159. public function getHandlerList()
  160. {
  161. return $this->handlerList;
  162. }
  163. public function getConfig($option = null)
  164. {
  165. return $option === null
  166. ? $this->config
  167. : (isset($this->config[$option])
  168. ? $this->config[$option]
  169. : null);
  170. }
  171. public function getCredentials()
  172. {
  173. $fn = $this->credentialProvider;
  174. return $fn();
  175. }
  176. public function getEndpoint()
  177. {
  178. return $this->endpoint;
  179. }
  180. public function getRegion()
  181. {
  182. return $this->region;
  183. }
  184. public function getApi()
  185. {
  186. return $this->api;
  187. }
  188. public function getCommand($name, array $args = [])
  189. {
  190. // Fail fast if the command cannot be found in the description.
  191. if (!isset($this->getApi()['operations'][$name])) {
  192. $name = ucfirst($name);
  193. if (!isset($this->getApi()['operations'][$name])) {
  194. throw new \InvalidArgumentException("Operation not found: $name");
  195. }
  196. }
  197. if (!isset($args['@http'])) {
  198. $args['@http'] = $this->defaultRequestOptions;
  199. } else {
  200. $args['@http'] += $this->defaultRequestOptions;
  201. }
  202. return new Command($name, $args, clone $this->getHandlerList());
  203. }
  204. public function __sleep()
  205. {
  206. throw new \RuntimeException('Instances of ' . static::class
  207. . ' cannot be serialized');
  208. }
  209. /**
  210. * Get the signature_provider function of the client.
  211. *
  212. * @return callable
  213. */
  214. final protected function getSignatureProvider()
  215. {
  216. return $this->signatureProvider;
  217. }
  218. /**
  219. * Parse the class name and setup the custom exception class of the client
  220. * and return the "service" name of the client and "exception_class".
  221. *
  222. * @return array
  223. */
  224. private function parseClass()
  225. {
  226. $klass = get_class($this);
  227. if ($klass === __CLASS__) {
  228. return ['', 'Aws\Exception\AwsException'];
  229. }
  230. $service = substr($klass, strrpos($klass, '\\') + 1, -6);
  231. return [
  232. strtolower($service),
  233. "Aws\\{$service}\\Exception\\{$service}Exception"
  234. ];
  235. }
  236. private function addSignatureMiddleware()
  237. {
  238. $api = $this->getApi();
  239. $provider = $this->signatureProvider;
  240. $version = $this->config['signature_version'];
  241. $name = $this->config['signing_name'];
  242. $region = $this->config['signing_region'];
  243. $resolver = static function (
  244. CommandInterface $c
  245. ) use ($api, $provider, $name, $region, $version) {
  246. $authType = $api->getOperation($c->getName())['authtype'];
  247. switch ($authType){
  248. case 'none':
  249. $version = 'anonymous';
  250. break;
  251. case 'v4-unsigned-body':
  252. $version = 'v4-unsigned-body';
  253. break;
  254. }
  255. return SignatureProvider::resolve($provider, $version, $name, $region);
  256. };
  257. $this->handlerList->appendSign(
  258. Middleware::signer($this->credentialProvider, $resolver),
  259. 'signer'
  260. );
  261. }
  262. private function addInvocationId()
  263. {
  264. // Add invocation id to each request
  265. $this->handlerList->prependSign(Middleware::invocationId(), 'invocation-id');
  266. }
  267. /**
  268. * Returns a service model and doc model with any necessary changes
  269. * applied.
  270. *
  271. * @param array $api Array of service data being documented.
  272. * @param array $docs Array of doc model data.
  273. *
  274. * @return array Tuple containing a [Service, DocModel]
  275. *
  276. * @internal This should only used to document the service API.
  277. * @codeCoverageIgnore
  278. */
  279. public static function applyDocFilters(array $api, array $docs)
  280. {
  281. return [
  282. new Service($api, ApiProvider::defaultProvider()),
  283. new DocModel($docs)
  284. ];
  285. }
  286. /**
  287. * @deprecated
  288. * @return static
  289. */
  290. public static function factory(array $config = [])
  291. {
  292. return new static($config);
  293. }
  294. }