PageRenderTime 25ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/src/AwsClient.php

https://gitlab.com/github-cloud-corp/aws-sdk-php
PHP | 317 lines | 173 code | 28 blank | 116 comment | 8 complexity | 2cb66baae9b13e65f5f85d1e60169330 MD5 | raw file
  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. * - profile: (string) Allows you to specify which profile to use when
  94. * credentials are created from the AWS credentials file in your HOME
  95. * directory. This setting overrides the AWS_PROFILE environment
  96. * variable. Note: Specifying "profile" will cause the "credentials" key
  97. * to be ignored.
  98. * - region: (string, required) Region to connect to. See
  99. * http://docs.aws.amazon.com/general/latest/gr/rande.html for a list of
  100. * available regions.
  101. * - retries: (int, default=int(3)) Configures the maximum number of
  102. * allowed retries for a client (pass 0 to disable retries).
  103. * - scheme: (string, default=string(5) "https") URI scheme to use when
  104. * connecting connect. The SDK will utilize "https" endpoints (i.e.,
  105. * utilize SSL/TLS connections) by default. You can attempt to connect to
  106. * a service over an unencrypted "http" endpoint by setting ``scheme`` to
  107. * "http".
  108. * - signature_provider: (callable) A callable that accepts a signature
  109. * version name (e.g., "v4"), a service name, and region, and
  110. * returns a SignatureInterface object or null. This provider is used to
  111. * create signers utilized by the client. See
  112. * Aws\Signature\SignatureProvider for a list of built-in providers
  113. * - signature_version: (string) A string representing a custom
  114. * signature version to use with a service (e.g., v4). Note that
  115. * per/operation signature version MAY override this requested signature
  116. * version.
  117. * - validate: (bool, default=bool(true)) Set to false to disable
  118. * client-side parameter validation.
  119. * - version: (string, required) The version of the webservice to
  120. * utilize (e.g., 2006-03-01).
  121. *
  122. * @param array $args Client configuration arguments.
  123. *
  124. * @throws \InvalidArgumentException if any required options are missing or
  125. * the service is not supported.
  126. */
  127. public function __construct(array $args)
  128. {
  129. list($service, $exceptionClass) = $this->parseClass();
  130. if (!isset($args['service'])) {
  131. $args['service'] = manifest($service)['endpoint'];
  132. }
  133. if (!isset($args['exception_class'])) {
  134. $args['exception_class'] = $exceptionClass;
  135. }
  136. $this->handlerList = new HandlerList();
  137. $resolver = new ClientResolver(static::getArguments());
  138. $config = $resolver->resolve($args, $this->handlerList);
  139. $this->api = $config['api'];
  140. $this->signatureProvider = $config['signature_provider'];
  141. $this->endpoint = new Uri($config['endpoint']);
  142. $this->credentialProvider = $config['credentials'];
  143. $this->region = isset($config['region']) ? $config['region'] : null;
  144. $this->config = $config['config'];
  145. $this->defaultRequestOptions = $config['http'];
  146. $this->addSignatureMiddleware();
  147. $this->addInvocationId();
  148. if (isset($args['with_resolved'])) {
  149. $args['with_resolved']($config);
  150. }
  151. }
  152. public function getHandlerList()
  153. {
  154. return $this->handlerList;
  155. }
  156. public function getConfig($option = null)
  157. {
  158. return $option === null
  159. ? $this->config
  160. : (isset($this->config[$option])
  161. ? $this->config[$option]
  162. : null);
  163. }
  164. public function getCredentials()
  165. {
  166. $fn = $this->credentialProvider;
  167. return $fn();
  168. }
  169. public function getEndpoint()
  170. {
  171. return $this->endpoint;
  172. }
  173. public function getRegion()
  174. {
  175. return $this->region;
  176. }
  177. public function getApi()
  178. {
  179. return $this->api;
  180. }
  181. public function getCommand($name, array $args = [])
  182. {
  183. // Fail fast if the command cannot be found in the description.
  184. if (!isset($this->getApi()['operations'][$name])) {
  185. $name = ucfirst($name);
  186. if (!isset($this->getApi()['operations'][$name])) {
  187. throw new \InvalidArgumentException("Operation not found: $name");
  188. }
  189. }
  190. if (!isset($args['@http'])) {
  191. $args['@http'] = $this->defaultRequestOptions;
  192. } else {
  193. $args['@http'] += $this->defaultRequestOptions;
  194. }
  195. return new Command($name, $args, clone $this->getHandlerList());
  196. }
  197. public function __sleep()
  198. {
  199. throw new \RuntimeException('Instances of ' . static::class
  200. . ' cannot be serialized');
  201. }
  202. /**
  203. * Get the signature_provider function of the client.
  204. *
  205. * @return callable
  206. */
  207. final protected function getSignatureProvider()
  208. {
  209. return $this->signatureProvider;
  210. }
  211. /**
  212. * Parse the class name and setup the custom exception class of the client
  213. * and return the "service" name of the client and "exception_class".
  214. *
  215. * @return array
  216. */
  217. private function parseClass()
  218. {
  219. $klass = get_class($this);
  220. if ($klass === __CLASS__) {
  221. return ['', 'Aws\Exception\AwsException'];
  222. }
  223. $service = substr($klass, strrpos($klass, '\\') + 1, -6);
  224. return [
  225. strtolower($service),
  226. "Aws\\{$service}\\Exception\\{$service}Exception"
  227. ];
  228. }
  229. private function addSignatureMiddleware()
  230. {
  231. $api = $this->getApi();
  232. $provider = $this->signatureProvider;
  233. $version = $this->config['signature_version'];
  234. $name = $this->config['signing_name'];
  235. $region = $this->config['signing_region'];
  236. $resolver = static function (
  237. CommandInterface $c
  238. ) use ($api, $provider, $name, $region, $version) {
  239. if ('none' === $api->getOperation($c->getName())['authtype']) {
  240. $version = 'anonymous';
  241. }
  242. return SignatureProvider::resolve($provider, $version, $name, $region);
  243. };
  244. $this->handlerList->appendSign(
  245. Middleware::signer($this->credentialProvider, $resolver),
  246. 'signer'
  247. );
  248. }
  249. private function addInvocationId()
  250. {
  251. // Add invocation id to each request
  252. $this->handlerList->prependSign(Middleware::invocationId(), 'invocation-id');
  253. }
  254. /**
  255. * Returns a service model and doc model with any necessary changes
  256. * applied.
  257. *
  258. * @param array $api Array of service data being documented.
  259. * @param array $docs Array of doc model data.
  260. *
  261. * @return array Tuple containing a [Service, DocModel]
  262. *
  263. * @internal This should only used to document the service API.
  264. * @codeCoverageIgnore
  265. */
  266. public static function applyDocFilters(array $api, array $docs)
  267. {
  268. return [
  269. new Service($api, ApiProvider::defaultProvider()),
  270. new DocModel($docs)
  271. ];
  272. }
  273. /**
  274. * @deprecated
  275. * @return static
  276. */
  277. public static function factory(array $config = [])
  278. {
  279. return new static($config);
  280. }
  281. }