ClientResolver.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. <?php
  2. namespace Aws;
  3. use Aws\Api\Validator;
  4. use Aws\Api\ApiProvider;
  5. use Aws\Api\Service;
  6. use Aws\Credentials\Credentials;
  7. use Aws\Credentials\CredentialsInterface;
  8. use Aws\Endpoint\Partition;
  9. use Aws\Endpoint\PartitionEndpointProvider;
  10. use Aws\Endpoint\PartitionProviderInterface;
  11. use Aws\Signature\SignatureProvider;
  12. use Aws\Endpoint\EndpointProvider;
  13. use Aws\Credentials\CredentialProvider;
  14. use GuzzleHttp\Promise;
  15. use InvalidArgumentException as IAE;
  16. use Psr\Http\Message\RequestInterface;
  17. /**
  18. * @internal Resolves a hash of client arguments to construct a client.
  19. */
  20. class ClientResolver
  21. {
  22. /** @var array */
  23. private $argDefinitions;
  24. /** @var array Map of types to a corresponding function */
  25. private static $typeMap = [
  26. 'resource' => 'is_resource',
  27. 'callable' => 'is_callable',
  28. 'int' => 'is_int',
  29. 'bool' => 'is_bool',
  30. 'string' => 'is_string',
  31. 'object' => 'is_object',
  32. 'array' => 'is_array',
  33. ];
  34. private static $defaultArgs = [
  35. 'service' => [
  36. 'type' => 'value',
  37. 'valid' => ['string'],
  38. 'doc' => 'Name of the service to utilize. This value will be supplied by default when using one of the SDK clients (e.g., Aws\\S3\\S3Client).',
  39. 'required' => true,
  40. 'internal' => true
  41. ],
  42. 'exception_class' => [
  43. 'type' => 'value',
  44. 'valid' => ['string'],
  45. 'doc' => 'Exception class to create when an error occurs.',
  46. 'default' => 'Aws\Exception\AwsException',
  47. 'internal' => true
  48. ],
  49. 'scheme' => [
  50. 'type' => 'value',
  51. 'valid' => ['string'],
  52. 'default' => 'https',
  53. 'doc' => 'URI scheme to use when connecting connect. The SDK will utilize "https" endpoints (i.e., utilize SSL/TLS connections) by default. You can attempt to connect to a service over an unencrypted "http" endpoint by setting ``scheme`` to "http".',
  54. ],
  55. 'endpoint' => [
  56. 'type' => 'value',
  57. 'valid' => ['string'],
  58. 'doc' => 'The full URI of the webservice. This is only required when connecting to a custom endpoint (e.g., a local version of S3).',
  59. 'fn' => [__CLASS__, '_apply_endpoint'],
  60. ],
  61. 'region' => [
  62. 'type' => 'value',
  63. 'valid' => ['string'],
  64. 'required' => [__CLASS__, '_missing_region'],
  65. 'doc' => 'Region to connect to. See http://docs.aws.amazon.com/general/latest/gr/rande.html for a list of available regions.',
  66. ],
  67. 'version' => [
  68. 'type' => 'value',
  69. 'valid' => ['string'],
  70. 'required' => [__CLASS__, '_missing_version'],
  71. 'doc' => 'The version of the webservice to utilize (e.g., 2006-03-01).',
  72. ],
  73. 'signature_provider' => [
  74. 'type' => 'value',
  75. 'valid' => ['callable'],
  76. 'doc' => 'A callable that accepts a signature version name (e.g., "v4"), a service name, and region, and returns a SignatureInterface object or null. This provider is used to create signers utilized by the client. See Aws\\Signature\\SignatureProvider for a list of built-in providers',
  77. 'default' => [__CLASS__, '_default_signature_provider'],
  78. ],
  79. 'api_provider' => [
  80. 'type' => 'value',
  81. 'valid' => ['callable'],
  82. 'doc' => 'An optional PHP callable that accepts a type, service, and version argument, and returns an array of corresponding configuration data. The type value can be one of api, waiter, or paginator.',
  83. 'fn' => [__CLASS__, '_apply_api_provider'],
  84. 'default' => [ApiProvider::class, 'defaultProvider'],
  85. ],
  86. 'endpoint_provider' => [
  87. 'type' => 'value',
  88. 'valid' => ['callable'],
  89. 'fn' => [__CLASS__, '_apply_endpoint_provider'],
  90. 'doc' => 'An optional PHP callable that accepts a hash of options including a "service" and "region" key and returns NULL or a hash of endpoint data, of which the "endpoint" key is required. See Aws\\Endpoint\\EndpointProvider for a list of built-in providers.',
  91. 'default' => [__CLASS__, '_default_endpoint_provider'],
  92. ],
  93. 'serializer' => [
  94. 'default' => [__CLASS__, '_default_serializer'],
  95. 'fn' => [__CLASS__, '_apply_serializer'],
  96. 'internal' => true,
  97. 'type' => 'value',
  98. 'valid' => ['callable'],
  99. ],
  100. 'signature_version' => [
  101. 'type' => 'config',
  102. 'valid' => ['string'],
  103. 'doc' => 'A string representing a custom signature version to use with a service (e.g., v4). Note that per/operation signature version MAY override this requested signature version.',
  104. 'default' => [__CLASS__, '_default_signature_version'],
  105. ],
  106. 'signing_name' => [
  107. 'type' => 'config',
  108. 'valid' => ['string'],
  109. 'doc' => 'A string representing a custom service name to be used when calculating a request signature.',
  110. 'default' => [__CLASS__, '_default_signing_name'],
  111. ],
  112. 'signing_region' => [
  113. 'type' => 'config',
  114. 'valid' => ['string'],
  115. 'doc' => 'A string representing a custom region name to be used when calculating a request signature.',
  116. 'default' => [__CLASS__, '_default_signing_region'],
  117. ],
  118. 'profile' => [
  119. 'type' => 'config',
  120. 'valid' => ['string'],
  121. 'doc' => 'Allows you to specify which profile to use when credentials are created from the AWS credentials file in your HOME directory. This setting overrides the AWS_PROFILE environment variable. Note: Specifying "profile" will cause the "credentials" key to be ignored.',
  122. 'fn' => [__CLASS__, '_apply_profile'],
  123. ],
  124. 'credentials' => [
  125. 'type' => 'value',
  126. 'valid' => [CredentialsInterface::class, CacheInterface::class, 'array', 'bool', 'callable'],
  127. 'doc' => 'Specifies the credentials used to sign requests. Provide an Aws\Credentials\CredentialsInterface object, an associative array of "key", "secret", and an optional "token" key, `false` to use null credentials, or a callable credentials provider used to create credentials or return null. See Aws\\Credentials\\CredentialProvider for a list of built-in credentials providers. If no credentials are provided, the SDK will attempt to load them from the environment.',
  128. 'fn' => [__CLASS__, '_apply_credentials'],
  129. 'default' => [CredentialProvider::class, 'defaultProvider'],
  130. ],
  131. 'stats' => [
  132. 'type' => 'value',
  133. 'valid' => ['bool', 'array'],
  134. 'default' => false,
  135. 'doc' => 'Set to true to gather transfer statistics on requests sent. Alternatively, you can provide an associative array with the following keys: retries: (bool) Set to false to disable reporting on retries attempted; http: (bool) Set to true to enable collecting statistics from lower level HTTP adapters (e.g., values returned in GuzzleHttp\TransferStats). HTTP handlers must support an http_stats_receiver option for this to have an effect; timer: (bool) Set to true to enable a command timer that reports the total wall clock time spent on an operation in seconds.',
  136. 'fn' => [__CLASS__, '_apply_stats'],
  137. ],
  138. 'retries' => [
  139. 'type' => 'value',
  140. 'valid' => ['int'],
  141. 'doc' => 'Configures the maximum number of allowed retries for a client (pass 0 to disable retries). ',
  142. 'fn' => [__CLASS__, '_apply_retries'],
  143. 'default' => 3,
  144. ],
  145. 'validate' => [
  146. 'type' => 'value',
  147. 'valid' => ['bool', 'array'],
  148. 'default' => true,
  149. 'doc' => 'Set to false to disable client-side parameter validation. Set to true to utilize default validation constraints. Set to an associative array of validation options to enable specific validation constraints.',
  150. 'fn' => [__CLASS__, '_apply_validate'],
  151. ],
  152. 'debug' => [
  153. 'type' => 'value',
  154. 'valid' => ['bool', 'array'],
  155. 'doc' => 'Set to true to display debug information when sending requests. Alternatively, you can provide an associative array with the following keys: logfn: (callable) Function that is invoked with log messages; stream_size: (int) When the size of a stream is greater than this number, the stream data will not be logged (set to "0" to not log any stream data); scrub_auth: (bool) Set to false to disable the scrubbing of auth data from the logged messages; http: (bool) Set to false to disable the "debug" feature of lower level HTTP adapters (e.g., verbose curl output).',
  156. 'fn' => [__CLASS__, '_apply_debug'],
  157. ],
  158. 'http' => [
  159. 'type' => 'value',
  160. 'valid' => ['array'],
  161. 'default' => [],
  162. 'doc' => 'Set to an array of SDK request options to apply to each request (e.g., proxy, verify, etc.).',
  163. ],
  164. 'http_handler' => [
  165. 'type' => 'value',
  166. 'valid' => ['callable'],
  167. 'doc' => 'An HTTP handler is a function that accepts a PSR-7 request object and returns a promise that is fulfilled with a PSR-7 response object or rejected with an array of exception data. NOTE: This option supersedes any provided "handler" option.',
  168. 'fn' => [__CLASS__, '_apply_http_handler']
  169. ],
  170. 'handler' => [
  171. 'type' => 'value',
  172. 'valid' => ['callable'],
  173. 'doc' => 'A handler that accepts a command object, request object and returns a promise that is fulfilled with an Aws\ResultInterface object or rejected with an Aws\Exception\AwsException. A handler does not accept a next handler as it is terminal and expected to fulfill a command. If no handler is provided, a default Guzzle handler will be utilized.',
  174. 'fn' => [__CLASS__, '_apply_handler'],
  175. 'default' => [__CLASS__, '_default_handler']
  176. ],
  177. 'ua_append' => [
  178. 'type' => 'value',
  179. 'valid' => ['string', 'array'],
  180. 'doc' => 'Provide a string or array of strings to send in the User-Agent header.',
  181. 'fn' => [__CLASS__, '_apply_user_agent'],
  182. 'default' => [],
  183. ],
  184. 'idempotency_auto_fill' => [
  185. 'type' => 'value',
  186. 'valid' => ['bool', 'callable'],
  187. 'doc' => 'Set to false to disable SDK to populate parameters that enabled \'idempotencyToken\' trait with a random UUID v4 value on your behalf. Using default value \'true\' still allows parameter value to be overwritten when provided. Note: auto-fill only works when cryptographically secure random bytes generator functions(random_bytes, openssl_random_pseudo_bytes or mcrypt_create_iv) can be found. You may also provide a callable source of random bytes.',
  188. 'default' => true,
  189. 'fn' => [__CLASS__, '_apply_idempotency_auto_fill']
  190. ],
  191. ];
  192. /**
  193. * Gets an array of default client arguments, each argument containing a
  194. * hash of the following:
  195. *
  196. * - type: (string, required) option type described as follows:
  197. * - value: The default option type.
  198. * - config: The provided value is made available in the client's
  199. * getConfig() method.
  200. * - valid: (array, required) Valid PHP types or class names. Note: null
  201. * is not an allowed type.
  202. * - required: (bool, callable) Whether or not the argument is required.
  203. * Provide a function that accepts an array of arguments and returns a
  204. * string to provide a custom error message.
  205. * - default: (mixed) The default value of the argument if not provided. If
  206. * a function is provided, then it will be invoked to provide a default
  207. * value. The function is provided the array of options and is expected
  208. * to return the default value of the option. The default value can be a
  209. * closure and can not be a callable string that is not part of the
  210. * defaultArgs array.
  211. * - doc: (string) The argument documentation string.
  212. * - fn: (callable) Function used to apply the argument. The function
  213. * accepts the provided value, array of arguments by reference, and an
  214. * event emitter.
  215. *
  216. * Note: Order is honored and important when applying arguments.
  217. *
  218. * @return array
  219. */
  220. public static function getDefaultArguments()
  221. {
  222. return self::$defaultArgs;
  223. }
  224. /**
  225. * @param array $argDefinitions Client arguments.
  226. */
  227. public function __construct(array $argDefinitions)
  228. {
  229. $this->argDefinitions = $argDefinitions;
  230. }
  231. /**
  232. * Resolves client configuration options and attached event listeners.
  233. * Check for missing keys in passed arguments
  234. *
  235. * @param array $args Provided constructor arguments.
  236. * @param HandlerList $list Handler list to augment.
  237. *
  238. * @return array Returns the array of provided options.
  239. * @throws \InvalidArgumentException
  240. * @see Aws\AwsClient::__construct for a list of available options.
  241. */
  242. public function resolve(array $args, HandlerList $list)
  243. {
  244. $args['config'] = [];
  245. foreach ($this->argDefinitions as $key => $a) {
  246. // Add defaults, validate required values, and skip if not set.
  247. if (!isset($args[$key])) {
  248. if (isset($a['default'])) {
  249. // Merge defaults in when not present.
  250. if (is_callable($a['default'])
  251. && (
  252. is_array($a['default'])
  253. || $a['default'] instanceof \Closure
  254. )
  255. ) {
  256. $args[$key] = $a['default']($args);
  257. } else {
  258. $args[$key] = $a['default'];
  259. }
  260. } elseif (empty($a['required'])) {
  261. continue;
  262. } else {
  263. $this->throwRequired($args);
  264. }
  265. }
  266. // Validate the types against the provided value.
  267. foreach ($a['valid'] as $check) {
  268. if (isset(self::$typeMap[$check])) {
  269. $fn = self::$typeMap[$check];
  270. if ($fn($args[$key])) {
  271. goto is_valid;
  272. }
  273. } elseif ($args[$key] instanceof $check) {
  274. goto is_valid;
  275. }
  276. }
  277. $this->invalidType($key, $args[$key]);
  278. // Apply the value
  279. is_valid:
  280. if (isset($a['fn'])) {
  281. $a['fn']($args[$key], $args, $list);
  282. }
  283. if ($a['type'] === 'config') {
  284. $args['config'][$key] = $args[$key];
  285. }
  286. }
  287. return $args;
  288. }
  289. /**
  290. * Creates a verbose error message for an invalid argument.
  291. *
  292. * @param string $name Name of the argument that is missing.
  293. * @param array $args Provided arguments
  294. * @param bool $useRequired Set to true to show the required fn text if
  295. * available instead of the documentation.
  296. * @return string
  297. */
  298. private function getArgMessage($name, $args = [], $useRequired = false)
  299. {
  300. $arg = $this->argDefinitions[$name];
  301. $msg = '';
  302. $modifiers = [];
  303. if (isset($arg['valid'])) {
  304. $modifiers[] = implode('|', $arg['valid']);
  305. }
  306. if (isset($arg['choice'])) {
  307. $modifiers[] = 'One of ' . implode(', ', $arg['choice']);
  308. }
  309. if ($modifiers) {
  310. $msg .= '(' . implode('; ', $modifiers) . ')';
  311. }
  312. $msg = wordwrap("{$name}: {$msg}", 75, "\n ");
  313. if ($useRequired && is_callable($arg['required'])) {
  314. $msg .= "\n\n ";
  315. $msg .= str_replace("\n", "\n ", call_user_func($arg['required'], $args));
  316. } elseif (isset($arg['doc'])) {
  317. $msg .= wordwrap("\n\n {$arg['doc']}", 75, "\n ");
  318. }
  319. return $msg;
  320. }
  321. /**
  322. * Throw when an invalid type is encountered.
  323. *
  324. * @param string $name Name of the value being validated.
  325. * @param mixed $provided The provided value.
  326. * @throws \InvalidArgumentException
  327. */
  328. private function invalidType($name, $provided)
  329. {
  330. $expected = implode('|', $this->argDefinitions[$name]['valid']);
  331. $msg = "Invalid configuration value "
  332. . "provided for \"{$name}\". Expected {$expected}, but got "
  333. . describe_type($provided) . "\n\n"
  334. . $this->getArgMessage($name);
  335. throw new IAE($msg);
  336. }
  337. /**
  338. * Throws an exception for missing required arguments.
  339. *
  340. * @param array $args Passed in arguments.
  341. * @throws \InvalidArgumentException
  342. */
  343. private function throwRequired(array $args)
  344. {
  345. $missing = [];
  346. foreach ($this->argDefinitions as $k => $a) {
  347. if (empty($a['required'])
  348. || isset($a['default'])
  349. || array_key_exists($k, $args)
  350. ) {
  351. continue;
  352. }
  353. $missing[] = $this->getArgMessage($k, $args, true);
  354. }
  355. $msg = "Missing required client configuration options: \n\n";
  356. $msg .= implode("\n\n", $missing);
  357. throw new IAE($msg);
  358. }
  359. public static function _apply_retries($value, array &$args, HandlerList $list)
  360. {
  361. if ($value) {
  362. $decider = RetryMiddleware::createDefaultDecider($value);
  363. $list->appendSign(
  364. Middleware::retry($decider, null, $args['stats']['retries']),
  365. 'retry'
  366. );
  367. }
  368. }
  369. public static function _apply_credentials($value, array &$args)
  370. {
  371. if (is_callable($value)) {
  372. return;
  373. } elseif ($value instanceof CredentialsInterface) {
  374. $args['credentials'] = CredentialProvider::fromCredentials($value);
  375. } elseif (is_array($value)
  376. && isset($value['key'])
  377. && isset($value['secret'])
  378. ) {
  379. $args['credentials'] = CredentialProvider::fromCredentials(
  380. new Credentials(
  381. $value['key'],
  382. $value['secret'],
  383. isset($value['token']) ? $value['token'] : null,
  384. isset($value['expires']) ? $value['expires'] : null
  385. )
  386. );
  387. } elseif ($value === false) {
  388. $args['credentials'] = CredentialProvider::fromCredentials(
  389. new Credentials('', '')
  390. );
  391. $args['config']['signature_version'] = 'anonymous';
  392. } elseif ($value instanceof CacheInterface) {
  393. $args['credentials'] = CredentialProvider::defaultProvider($args);
  394. } else {
  395. throw new IAE('Credentials must be an instance of '
  396. . 'Aws\Credentials\CredentialsInterface, an associative '
  397. . 'array that contains "key", "secret", and an optional "token" '
  398. . 'key-value pairs, a credentials provider function, or false.');
  399. }
  400. }
  401. public static function _apply_api_provider(callable $value, array &$args)
  402. {
  403. $api = new Service(
  404. ApiProvider::resolve(
  405. $value,
  406. 'api',
  407. $args['service'],
  408. $args['version']
  409. ),
  410. $value
  411. );
  412. if (
  413. empty($args['config']['signing_name'])
  414. && isset($api['metadata']['signingName'])
  415. ) {
  416. $args['config']['signing_name'] = $api['metadata']['signingName'];
  417. }
  418. $args['api'] = $api;
  419. $args['parser'] = Service::createParser($api);
  420. $args['error_parser'] = Service::createErrorParser($api->getProtocol());
  421. }
  422. public static function _apply_endpoint_provider(callable $value, array &$args)
  423. {
  424. if (!isset($args['endpoint'])) {
  425. $endpointPrefix = isset($args['api']['metadata']['endpointPrefix'])
  426. ? $args['api']['metadata']['endpointPrefix']
  427. : $args['service'];
  428. // Invoke the endpoint provider and throw if it does not resolve.
  429. $result = EndpointProvider::resolve($value, [
  430. 'service' => $endpointPrefix,
  431. 'region' => $args['region'],
  432. 'scheme' => $args['scheme']
  433. ]);
  434. $args['endpoint'] = $result['endpoint'];
  435. if (
  436. empty($args['config']['signature_version'])
  437. && isset($result['signatureVersion'])
  438. ) {
  439. $args['config']['signature_version']
  440. = $result['signatureVersion'];
  441. }
  442. if (
  443. empty($args['config']['signing_region'])
  444. && isset($result['signingRegion'])
  445. ) {
  446. $args['config']['signing_region'] = $result['signingRegion'];
  447. }
  448. if (
  449. empty($args['config']['signing_name'])
  450. && isset($result['signingName'])
  451. ) {
  452. $args['config']['signing_name'] = $result['signingName'];
  453. }
  454. }
  455. }
  456. public static function _apply_serializer($value, array &$args, HandlerList $list)
  457. {
  458. $list->prependBuild(Middleware::requestBuilder($value), 'builder');
  459. }
  460. public static function _apply_debug($value, array &$args, HandlerList $list)
  461. {
  462. if ($value !== false) {
  463. $list->interpose(new TraceMiddleware($value === true ? [] : $value));
  464. }
  465. }
  466. public static function _apply_stats($value, array &$args, HandlerList $list)
  467. {
  468. // Create an array of stat collectors that are disabled (set to false)
  469. // by default. If the user has passed in true, enable all stat
  470. // collectors.
  471. $defaults = array_fill_keys(
  472. ['http', 'retries', 'timer'],
  473. $value === true
  474. );
  475. $args['stats'] = is_array($value)
  476. ? array_replace($defaults, $value)
  477. : $defaults;
  478. if ($args['stats']['timer']) {
  479. $list->prependInit(Middleware::timer(), 'timer');
  480. }
  481. }
  482. public static function _apply_profile($_, array &$args)
  483. {
  484. $args['credentials'] = CredentialProvider::ini($args['profile']);
  485. }
  486. public static function _apply_validate($value, array &$args, HandlerList $list)
  487. {
  488. if ($value === false) {
  489. return;
  490. }
  491. $validator = $value === true
  492. ? new Validator()
  493. : new Validator($value);
  494. $list->appendValidate(
  495. Middleware::validation($args['api'], $validator),
  496. 'validation'
  497. );
  498. }
  499. public static function _apply_handler($value, array &$args, HandlerList $list)
  500. {
  501. $list->setHandler($value);
  502. }
  503. public static function _default_handler(array &$args)
  504. {
  505. return new WrappedHttpHandler(
  506. default_http_handler(),
  507. $args['parser'],
  508. $args['error_parser'],
  509. $args['exception_class'],
  510. $args['stats']['http']
  511. );
  512. }
  513. public static function _apply_http_handler($value, array &$args, HandlerList $list)
  514. {
  515. $args['handler'] = new WrappedHttpHandler(
  516. $value,
  517. $args['parser'],
  518. $args['error_parser'],
  519. $args['exception_class'],
  520. $args['stats']['http']
  521. );
  522. }
  523. public static function _apply_user_agent($value, array &$args, HandlerList $list)
  524. {
  525. if (!is_array($value)) {
  526. $value = [$value];
  527. }
  528. $value = array_map('strval', $value);
  529. array_unshift($value, 'aws-sdk-php/' . Sdk::VERSION);
  530. $args['ua_append'] = $value;
  531. $list->appendBuild(static function (callable $handler) use ($value) {
  532. return function (
  533. CommandInterface $command,
  534. RequestInterface $request
  535. ) use ($handler, $value) {
  536. return $handler($command, $request->withHeader(
  537. 'User-Agent',
  538. implode(' ', array_merge(
  539. $value,
  540. $request->getHeader('User-Agent')
  541. ))
  542. ));
  543. };
  544. });
  545. }
  546. public static function _apply_endpoint($value, array &$args, HandlerList $list)
  547. {
  548. $parts = parse_url($value);
  549. if (empty($parts['scheme']) || empty($parts['host'])) {
  550. throw new IAE(
  551. 'Endpoints must be full URIs and include a scheme and host'
  552. );
  553. }
  554. $args['endpoint'] = $value;
  555. }
  556. public static function _apply_idempotency_auto_fill(
  557. $value,
  558. array &$args,
  559. HandlerList $list
  560. ) {
  561. $enabled = false;
  562. $generator = null;
  563. if (is_bool($value)) {
  564. $enabled = $value;
  565. } elseif (is_callable($value)) {
  566. $enabled = true;
  567. $generator = $value;
  568. }
  569. if ($enabled) {
  570. $list->prependInit(
  571. IdempotencyTokenMiddleware::wrap($args['api'], $generator),
  572. 'idempotency_auto_fill'
  573. );
  574. }
  575. }
  576. public static function _default_endpoint_provider(array $args)
  577. {
  578. return PartitionEndpointProvider::defaultProvider()
  579. ->getPartition($args['region'], $args['service']);
  580. }
  581. public static function _default_serializer(array $args)
  582. {
  583. return Service::createSerializer(
  584. $args['api'],
  585. $args['endpoint']
  586. );
  587. }
  588. public static function _default_signature_provider()
  589. {
  590. return SignatureProvider::defaultProvider();
  591. }
  592. public static function _default_signature_version(array &$args)
  593. {
  594. if (isset($args['config']['signature_version'])) {
  595. return $args['config']['signature_version'];
  596. }
  597. $args['__partition_result'] = isset($args['__partition_result'])
  598. ? isset($args['__partition_result'])
  599. : call_user_func(PartitionEndpointProvider::defaultProvider(), [
  600. 'service' => $args['service'],
  601. 'region' => $args['region'],
  602. ]);
  603. return isset($args['__partition_result']['signatureVersion'])
  604. ? $args['__partition_result']['signatureVersion']
  605. : $args['api']->getSignatureVersion();
  606. }
  607. public static function _default_signing_name(array &$args)
  608. {
  609. if (isset($args['config']['signing_name'])) {
  610. return $args['config']['signing_name'];
  611. }
  612. $args['__partition_result'] = isset($args['__partition_result'])
  613. ? isset($args['__partition_result'])
  614. : call_user_func(PartitionEndpointProvider::defaultProvider(), [
  615. 'service' => $args['service'],
  616. 'region' => $args['region'],
  617. ]);
  618. if (isset($args['__partition_result']['signingName'])) {
  619. return $args['__partition_result']['signingName'];
  620. }
  621. if ($signingName = $args['api']->getSigningName()) {
  622. return $signingName;
  623. }
  624. return $args['service'];
  625. }
  626. public static function _default_signing_region(array &$args)
  627. {
  628. if (isset($args['config']['signing_region'])) {
  629. return $args['config']['signing_region'];
  630. }
  631. $args['__partition_result'] = isset($args['__partition_result'])
  632. ? isset($args['__partition_result'])
  633. : call_user_func(PartitionEndpointProvider::defaultProvider(), [
  634. 'service' => $args['service'],
  635. 'region' => $args['region'],
  636. ]);
  637. return isset($args['__partition_result']['signingRegion'])
  638. ? $args['__partition_result']['signingRegion']
  639. : $args['region'];
  640. }
  641. public static function _missing_version(array $args)
  642. {
  643. $service = isset($args['service']) ? $args['service'] : '';
  644. $versions = ApiProvider::defaultProvider()->getVersions($service);
  645. $versions = implode("\n", array_map(function ($v) {
  646. return "* \"$v\"";
  647. }, $versions)) ?: '* (none found)';
  648. return <<<EOT
  649. A "version" configuration value is required. Specifying a version constraint
  650. ensures that your code will not be affected by a breaking change made to the
  651. service. For example, when using Amazon S3, you can lock your API version to
  652. "2006-03-01".
  653. Your build of the SDK has the following version(s) of "{$service}": {$versions}
  654. You may provide "latest" to the "version" configuration value to utilize the
  655. most recent available API version that your client's API provider can find.
  656. Note: Using 'latest' in a production application is not recommended.
  657. A list of available API versions can be found on each client's API documentation
  658. page: http://docs.aws.amazon.com/aws-sdk-php/v3/api/index.html. If you are
  659. unable to load a specific API version, then you may need to update your copy of
  660. the SDK.
  661. EOT;
  662. }
  663. public static function _missing_region(array $args)
  664. {
  665. $service = isset($args['service']) ? $args['service'] : '';
  666. return <<<EOT
  667. A "region" configuration value is required for the "{$service}" service
  668. (e.g., "us-west-2"). A list of available public regions and endpoints can be
  669. found at http://docs.aws.amazon.com/general/latest/gr/rande.html.
  670. EOT;
  671. }
  672. }