PluginProbe
Media Cloud Sync / 1.2.12
Media Cloud Sync v1.2.12
1.4.0 1.3.12 1.3.11 1.3.10 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.1.0 1.1.1 1.2.0 1.2.10 1.2.11 1.2.12 1.2.13 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 1.2.9 1.3.0 All 34 releases
media-cloud-sync / includes / sdk / s3 / Aws / ClientResolver.php

ClientResolver.php in Media Cloud Sync 1.2.12, at includes/sdk/s3/Aws/ClientResolver.php

569 lines 38.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Dudlewebs\WPMCS\s3\Aws;
4
5 use Dudlewebs\WPMCS\s3\Aws\Api\Validator;
6 use Dudlewebs\WPMCS\s3\Aws\Api\ApiProvider;
7 use Dudlewebs\WPMCS\s3\Aws\Api\Service;
8 use Dudlewebs\WPMCS\s3\Aws\ClientSideMonitoring\ApiCallAttemptMonitoringMiddleware;
9 use Dudlewebs\WPMCS\s3\Aws\ClientSideMonitoring\ApiCallMonitoringMiddleware;
10 use Dudlewebs\WPMCS\s3\Aws\ClientSideMonitoring\Configuration;
11 use Dudlewebs\WPMCS\s3\Aws\Credentials\Credentials;
12 use Dudlewebs\WPMCS\s3\Aws\Credentials\CredentialsInterface;
13 use Dudlewebs\WPMCS\s3\Aws\Endpoint\PartitionEndpointProvider;
14 use Dudlewebs\WPMCS\s3\Aws\Endpoint\UseFipsEndpoint\Configuration as UseFipsEndpointConfiguration;
15 use Dudlewebs\WPMCS\s3\Aws\Endpoint\UseFipsEndpoint\ConfigurationProvider as UseFipsConfigProvider;
16 use Dudlewebs\WPMCS\s3\Aws\Endpoint\UseFipsEndpoint\ConfigurationInterface as UseFipsEndpointConfigurationInterface;
17 use Dudlewebs\WPMCS\s3\Aws\Endpoint\UseDualstackEndpoint\Configuration as UseDualStackEndpointConfiguration;
18 use Dudlewebs\WPMCS\s3\Aws\Endpoint\UseDualstackEndpoint\ConfigurationProvider as UseDualStackConfigProvider;
19 use Dudlewebs\WPMCS\s3\Aws\Endpoint\UseDualstackEndpoint\ConfigurationInterface as UseDualStackEndpointConfigurationInterface;
20 use Dudlewebs\WPMCS\s3\Aws\EndpointDiscovery\ConfigurationInterface;
21 use Dudlewebs\WPMCS\s3\Aws\EndpointDiscovery\ConfigurationProvider;
22 use Dudlewebs\WPMCS\s3\Aws\Exception\InvalidRegionException;
23 use Dudlewebs\WPMCS\s3\Aws\Retry\ConfigurationInterface as RetryConfigInterface;
24 use Dudlewebs\WPMCS\s3\Aws\Retry\ConfigurationProvider as RetryConfigProvider;
25 use Dudlewebs\WPMCS\s3\Aws\DefaultsMode\ConfigurationInterface as ConfigModeInterface;
26 use Dudlewebs\WPMCS\s3\Aws\DefaultsMode\ConfigurationProvider as ConfigModeProvider;
27 use Dudlewebs\WPMCS\s3\Aws\Signature\SignatureProvider;
28 use Dudlewebs\WPMCS\s3\Aws\Endpoint\EndpointProvider;
29 use Dudlewebs\WPMCS\s3\GuzzleHttp\Promise\PromiseInterface;
30 use Dudlewebs\WPMCS\s3\Aws\Credentials\CredentialProvider;
31 use InvalidArgumentException as IAE;
32 use Dudlewebs\WPMCS\s3\Psr\Http\Message\RequestInterface;
33 /**
34 * @internal Resolves a hash of client arguments to construct a client.
35 */
36 class ClientResolver
37 {
38 /** @var array */
39 private $argDefinitions;
40 /** @var array Map of types to a corresponding function */
41 private static $typeMap = ['resource' => 'is_resource', 'callable' => 'is_callable', 'int' => 'is_int', 'bool' => 'is_bool', 'string' => 'is_string', 'object' => 'is_object', 'array' => 'is_array'];
42 private static $defaultArgs = ['service' => ['type' => 'value', 'valid' => ['string'], '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).', 'required' => \true, 'internal' => \true], 'exception_class' => ['type' => 'value', 'valid' => ['string'], 'doc' => 'Exception class to create when an error occurs.', 'default' => 'Dudlewebs\\WPMCS\\s3\\Aws\\Exception\\AwsException', 'internal' => \true], 'scheme' => ['type' => 'value', 'valid' => ['string'], 'default' => 'https', '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".'], 'disable_host_prefix_injection' => ['type' => 'value', 'valid' => ['bool'], 'doc' => 'Set to true to disable host prefix injection logic for services that use it. This disables the entire prefix injection, including the portions supplied by user-defined parameters. Setting this flag will have no effect on services that do not use host prefix injection.', 'default' => \false], 'endpoint' => ['type' => 'value', 'valid' => ['string'], 'doc' => 'The full URI of the webservice. This is only required when connecting to a custom endpoint (e.g., a local version of S3).', 'fn' => [__CLASS__, '_apply_endpoint']], 'region' => ['type' => 'value', 'valid' => ['string'], 'required' => [__CLASS__, '_missing_region'], 'doc' => 'Region to connect to. See http://docs.aws.amazon.com/general/latest/gr/rande.html for a list of available regions.'], 'version' => ['type' => 'value', 'valid' => ['string'], 'required' => [__CLASS__, '_missing_version'], 'doc' => 'The version of the webservice to utilize (e.g., 2006-03-01).'], 'signature_provider' => ['type' => 'value', 'valid' => ['callable'], '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', 'default' => [__CLASS__, '_default_signature_provider']], 'api_provider' => ['type' => 'value', 'valid' => ['callable'], '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.', 'fn' => [__CLASS__, '_apply_api_provider'], 'default' => [ApiProvider::class, 'defaultProvider']], 'configuration_mode' => ['type' => 'value', 'valid' => [ConfigModeInterface::class, CacheInterface::class, 'string', 'closure'], 'doc' => "Sets the default configuration mode. Otherwise provide an instance of Aws\\DefaultsMode\\ConfigurationInterface, an instance of Aws\\CacheInterface, or a string containing a valid mode", 'fn' => [__CLASS__, '_apply_defaults'], 'default' => [ConfigModeProvider::class, 'defaultProvider']], 'use_fips_endpoint' => ['type' => 'value', 'valid' => ['bool', UseFipsEndpointConfiguration::class, CacheInterface::class, 'callable'], 'doc' => 'Set to true to enable the use of FIPS pseudo regions', 'fn' => [__CLASS__, '_apply_use_fips_endpoint'], 'default' => [__CLASS__, '_default_use_fips_endpoint']], 'use_dual_stack_endpoint' => ['type' => 'value', 'valid' => ['bool', UseDualStackEndpointConfiguration::class, CacheInterface::class, 'callable'], 'doc' => 'Set to true to enable the use of dual-stack endpoints', 'fn' => [__CLASS__, '_apply_use_dual_stack_endpoint'], 'default' => [__CLASS__, '_default_use_dual_stack_endpoint']], 'endpoint_provider' => ['type' => 'value', 'valid' => ['callable'], 'fn' => [__CLASS__, '_apply_endpoint_provider'], '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.', 'default' => [__CLASS__, '_default_endpoint_provider']], 'serializer' => ['default' => [__CLASS__, '_default_serializer'], 'fn' => [__CLASS__, '_apply_serializer'], 'internal' => \true, 'type' => 'value', 'valid' => ['callable']], 'signature_version' => ['type' => 'config', 'valid' => ['string'], '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.', 'default' => [__CLASS__, '_default_signature_version']], 'signing_name' => ['type' => 'config', 'valid' => ['string'], 'doc' => 'A string representing a custom service name to be used when calculating a request signature.', 'default' => [__CLASS__, '_default_signing_name']], 'signing_region' => ['type' => 'config', 'valid' => ['string'], 'doc' => 'A string representing a custom region name to be used when calculating a request signature.', 'default' => [__CLASS__, '_default_signing_region']], 'profile' => ['type' => 'config', 'valid' => ['string'], '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" and "use_aws_shared_config_files" keys to be ignored.', 'fn' => [__CLASS__, '_apply_profile']], 'credentials' => ['type' => 'value', 'valid' => [CredentialsInterface::class, CacheInterface::class, 'array', 'bool', 'callable'], '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.', 'fn' => [__CLASS__, '_apply_credentials'], 'default' => [__CLASS__, '_default_credential_provider']], 'endpoint_discovery' => ['type' => 'value', 'valid' => [ConfigurationInterface::class, CacheInterface::class, 'array', 'callable'], 'doc' => 'Specifies settings for endpoint discovery. Provide an instance of Aws\\EndpointDiscovery\\ConfigurationInterface, an instance Aws\\CacheInterface, a callable that provides a promise for a Configuration object, or an associative array with the following keys: enabled: (bool) Set to true to enable endpoint discovery, false to explicitly disable it. Defaults to false; cache_limit: (int) The maximum number of keys in the endpoints cache. Defaults to 1000.', 'fn' => [__CLASS__, '_apply_endpoint_discovery'], 'default' => [__CLASS__, '_default_endpoint_discovery_provider']], 'stats' => ['type' => 'value', 'valid' => ['bool', 'array'], 'default' => \false, '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.', 'fn' => [__CLASS__, '_apply_stats']], 'retries' => ['type' => 'value', 'valid' => ['int', RetryConfigInterface::class, CacheInterface::class, 'callable', 'array'], 'doc' => "Configures the retry mode and maximum number of allowed retries for a client (pass 0 to disable retries). Provide an integer for 'legacy' mode with the specified number of retries. Otherwise provide an instance of Aws\\Retry\\ConfigurationInterface, an instance of Aws\\CacheInterface, a callable function, or an array with the following keys: mode: (string) Set to 'legacy', 'standard' (uses retry quota management), or 'adapative' (an experimental mode that adds client-side rate limiting to standard mode); max_attempts: (int) The maximum number of attempts for a given request. ", 'fn' => [__CLASS__, '_apply_retries'], 'default' => [RetryConfigProvider::class, 'defaultProvider']], 'validate' => ['type' => 'value', 'valid' => ['bool', 'array'], 'default' => \true, '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.', 'fn' => [__CLASS__, '_apply_validate']], 'debug' => ['type' => 'value', 'valid' => ['bool', 'array'], '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).', 'fn' => [__CLASS__, '_apply_debug']], 'csm' => ['type' => 'value', 'valid' => [\Dudlewebs\WPMCS\s3\Aws\ClientSideMonitoring\ConfigurationInterface::class, 'callable', 'array', 'bool'], 'doc' => 'CSM options for the client. Provides a callable wrapping a promise, a boolean "false", an instance of ConfigurationInterface, or an associative array of "enabled", "host", "port", and "client_id".', 'fn' => [__CLASS__, '_apply_csm'], 'default' => [\Dudlewebs\WPMCS\s3\Aws\ClientSideMonitoring\ConfigurationProvider::class, 'defaultProvider']], 'http' => ['type' => 'value', 'valid' => ['array'], 'default' => [], 'doc' => 'Set to an array of SDK request options to apply to each request (e.g., proxy, verify, etc.).'], 'http_handler' => ['type' => 'value', 'valid' => ['callable'], '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.', 'fn' => [__CLASS__, '_apply_http_handler']], 'handler' => ['type' => 'value', 'valid' => ['callable'], '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.', 'fn' => [__CLASS__, '_apply_handler'], 'default' => [__CLASS__, '_default_handler']], 'ua_append' => ['type' => 'value', 'valid' => ['string', 'array'], 'doc' => 'Provide a string or array of strings to send in the User-Agent header.', 'fn' => [__CLASS__, '_apply_user_agent'], 'default' => []], 'idempotency_auto_fill' => ['type' => 'value', 'valid' => ['bool', 'callable'], '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.', 'default' => \true, 'fn' => [__CLASS__, '_apply_idempotency_auto_fill']], 'use_aws_shared_config_files' => ['type' => 'value', 'valid' => ['bool'], 'doc' => 'Set to false to disable checking for shared aws config files usually located in \'~/.aws/config\' and \'~/.aws/credentials\'. This will be ignored if you set the \'profile\' setting.', 'default' => \true]];
43 /**
44 * Gets an array of default client arguments, each argument containing a
45 * hash of the following:
46 *
47 * - type: (string, required) option type described as follows:
48 * - value: The default option type.
49 * - config: The provided value is made available in the client's
50 * getConfig() method.
51 * - valid: (array, required) Valid PHP types or class names. Note: null
52 * is not an allowed type.
53 * - required: (bool, callable) Whether or not the argument is required.
54 * Provide a function that accepts an array of arguments and returns a
55 * string to provide a custom error message.
56 * - default: (mixed) The default value of the argument if not provided. If
57 * a function is provided, then it will be invoked to provide a default
58 * value. The function is provided the array of options and is expected
59 * to return the default value of the option. The default value can be a
60 * closure and can not be a callable string that is not part of the
61 * defaultArgs array.
62 * - doc: (string) The argument documentation string.
63 * - fn: (callable) Function used to apply the argument. The function
64 * accepts the provided value, array of arguments by reference, and an
65 * event emitter.
66 *
67 * Note: Order is honored and important when applying arguments.
68 *
69 * @return array
70 */
71 public static function getDefaultArguments()
72 {
73 return self::$defaultArgs;
74 }
75 /**
76 * @param array $argDefinitions Client arguments.
77 */
78 public function __construct(array $argDefinitions)
79 {
80 $this->argDefinitions = $argDefinitions;
81 }
82 /**
83 * Resolves client configuration options and attached event listeners.
84 * Check for missing keys in passed arguments
85 *
86 * @param array $args Provided constructor arguments.
87 * @param HandlerList $list Handler list to augment.
88 *
89 * @return array Returns the array of provided options.
90 * @throws \InvalidArgumentException
91 * @see Aws\AwsClient::__construct for a list of available options.
92 */
93 public function resolve(array $args, HandlerList $list)
94 {
95 $args['config'] = [];
96 foreach ($this->argDefinitions as $key => $a) {
97 // Add defaults, validate required values, and skip if not set.
98 if (!isset($args[$key])) {
99 if (isset($a['default'])) {
100 // Merge defaults in when not present.
101 if (\is_callable($a['default']) && (\is_array($a['default']) || $a['default'] instanceof \Closure)) {
102 $args[$key] = $a['default']($args);
103 } else {
104 $args[$key] = $a['default'];
105 }
106 } elseif (empty($a['required'])) {
107 continue;
108 } else {
109 $this->throwRequired($args);
110 }
111 }
112 // Validate the types against the provided value.
113 foreach ($a['valid'] as $check) {
114 if (isset(self::$typeMap[$check])) {
115 $fn = self::$typeMap[$check];
116 if ($fn($args[$key])) {
117 goto is_valid;
118 }
119 } elseif ($args[$key] instanceof $check) {
120 goto is_valid;
121 }
122 }
123 $this->invalidType($key, $args[$key]);
124 // Apply the value
125 is_valid:
126 if (isset($a['fn'])) {
127 $a['fn']($args[$key], $args, $list);
128 }
129 if ($a['type'] === 'config') {
130 $args['config'][$key] = $args[$key];
131 }
132 }
133 return $args;
134 }
135 /**
136 * Creates a verbose error message for an invalid argument.
137 *
138 * @param string $name Name of the argument that is missing.
139 * @param array $args Provided arguments
140 * @param bool $useRequired Set to true to show the required fn text if
141 * available instead of the documentation.
142 * @return string
143 */
144 private function getArgMessage($name, $args = [], $useRequired = \false)
145 {
146 $arg = $this->argDefinitions[$name];
147 $msg = '';
148 $modifiers = [];
149 if (isset($arg['valid'])) {
150 $modifiers[] = \implode('|', $arg['valid']);
151 }
152 if (isset($arg['choice'])) {
153 $modifiers[] = 'One of ' . \implode(', ', $arg['choice']);
154 }
155 if ($modifiers) {
156 $msg .= '(' . \implode('; ', $modifiers) . ')';
157 }
158 $msg = \wordwrap("{$name}: {$msg}", 75, "\n ");
159 if ($useRequired && \is_callable($arg['required'])) {
160 $msg .= "\n\n ";
161 $msg .= \str_replace("\n", "\n ", \call_user_func($arg['required'], $args));
162 } elseif (isset($arg['doc'])) {
163 $msg .= \wordwrap("\n\n {$arg['doc']}", 75, "\n ");
164 }
165 return $msg;
166 }
167 /**
168 * Throw when an invalid type is encountered.
169 *
170 * @param string $name Name of the value being validated.
171 * @param mixed $provided The provided value.
172 * @throws \InvalidArgumentException
173 */
174 private function invalidType($name, $provided)
175 {
176 $expected = \implode('|', $this->argDefinitions[$name]['valid']);
177 $msg = "Invalid configuration value " . "provided for \"{$name}\". Expected {$expected}, but got " . describe_type($provided) . "\n\n" . $this->getArgMessage($name);
178 throw new IAE($msg);
179 }
180 /**
181 * Throws an exception for missing required arguments.
182 *
183 * @param array $args Passed in arguments.
184 * @throws \InvalidArgumentException
185 */
186 private function throwRequired(array $args)
187 {
188 $missing = [];
189 foreach ($this->argDefinitions as $k => $a) {
190 if (empty($a['required']) || isset($a['default']) || isset($args[$k])) {
191 continue;
192 }
193 $missing[] = $this->getArgMessage($k, $args, \true);
194 }
195 $msg = "Missing required client configuration options: \n\n";
196 $msg .= \implode("\n\n", $missing);
197 throw new IAE($msg);
198 }
199 public static function _apply_retries($value, array &$args, HandlerList $list)
200 {
201 // A value of 0 for the config option disables retries
202 if ($value) {
203 $config = RetryConfigProvider::unwrap($value);
204 if ($config->getMode() === 'legacy') {
205 // # of retries is 1 less than # of attempts
206 $decider = RetryMiddleware::createDefaultDecider($config->getMaxAttempts() - 1);
207 $list->appendSign(Middleware::retry($decider, null, $args['stats']['retries']), 'retry');
208 } else {
209 $list->appendSign(RetryMiddlewareV2::wrap($config, ['collect_stats' => $args['stats']['retries']]), 'retry');
210 }
211 }
212 }
213 public static function _apply_defaults($value, array &$args, HandlerList $list)
214 {
215 $config = ConfigModeProvider::unwrap($value);
216 if ($config->getMode() !== 'legacy') {
217 if (!isset($args['retries']) && !\is_null($config->getRetryMode())) {
218 $args['retries'] = ['mode' => $config->getRetryMode()];
219 }
220 if (!isset($args['sts_regional_endpoints']) && !\is_null($config->getStsRegionalEndpoints())) {
221 $args['sts_regional_endpoints'] = ['mode' => $config->getStsRegionalEndpoints()];
222 }
223 if (!isset($args['s3_us_east_1_regional_endpoint']) && !\is_null($config->getS3UsEast1RegionalEndpoints())) {
224 $args['s3_us_east_1_regional_endpoint'] = ['mode' => $config->getS3UsEast1RegionalEndpoints()];
225 }
226 if (!isset($args['http'])) {
227 $args['http'] = [];
228 }
229 if (!isset($args['http']['connect_timeout']) && !\is_null($config->getConnectTimeoutInMillis())) {
230 $args['http']['connect_timeout'] = $config->getConnectTimeoutInMillis() / 1000;
231 }
232 if (!isset($args['http']['timeout']) && !\is_null($config->getHttpRequestTimeoutInMillis())) {
233 $args['http']['timeout'] = $config->getHttpRequestTimeoutInMillis() / 1000;
234 }
235 }
236 }
237 public static function _apply_credentials($value, array &$args)
238 {
239 if (\is_callable($value)) {
240 return;
241 }
242 if ($value instanceof CredentialsInterface) {
243 $args['credentials'] = CredentialProvider::fromCredentials($value);
244 } elseif (\is_array($value) && isset($value['key']) && isset($value['secret'])) {
245 $args['credentials'] = CredentialProvider::fromCredentials(new Credentials($value['key'], $value['secret'], isset($value['token']) ? $value['token'] : null, isset($value['expires']) ? $value['expires'] : null));
246 } elseif ($value === \false) {
247 $args['credentials'] = CredentialProvider::fromCredentials(new Credentials('', ''));
248 $args['config']['signature_version'] = 'anonymous';
249 } elseif ($value instanceof CacheInterface) {
250 $args['credentials'] = CredentialProvider::defaultProvider($args);
251 } else {
252 throw new IAE('Credentials must be an instance of ' . 'Dudlewebs\\WPMCS\\s3\\Aws\\Credentials\\CredentialsInterface, an associative ' . 'array that contains "key", "secret", and an optional "token" ' . 'key-value pairs, a credentials provider function, or false.');
253 }
254 }
255 public static function _default_credential_provider(array $args)
256 {
257 return CredentialProvider::defaultProvider($args);
258 }
259 public static function _apply_csm($value, array &$args, HandlerList $list)
260 {
261 if ($value === \false) {
262 $value = new Configuration(\false, \Dudlewebs\WPMCS\s3\Aws\ClientSideMonitoring\ConfigurationProvider::DEFAULT_HOST, \Dudlewebs\WPMCS\s3\Aws\ClientSideMonitoring\ConfigurationProvider::DEFAULT_PORT, \Dudlewebs\WPMCS\s3\Aws\ClientSideMonitoring\ConfigurationProvider::DEFAULT_CLIENT_ID);
263 $args['csm'] = $value;
264 }
265 $list->appendBuild(ApiCallMonitoringMiddleware::wrap($args['credentials'], $value, $args['region'], $args['api']->getServiceId()), 'ApiCallMonitoringMiddleware');
266 $list->appendAttempt(ApiCallAttemptMonitoringMiddleware::wrap($args['credentials'], $value, $args['region'], $args['api']->getServiceId()), 'ApiCallAttemptMonitoringMiddleware');
267 }
268 public static function _apply_api_provider(callable $value, array &$args)
269 {
270 $api = new Service(ApiProvider::resolve($value, 'api', $args['service'], $args['version']), $value);
271 if (empty($args['config']['signing_name']) && isset($api['metadata']['signingName'])) {
272 $args['config']['signing_name'] = $api['metadata']['signingName'];
273 }
274 $args['api'] = $api;
275 $args['parser'] = Service::createParser($api);
276 $args['error_parser'] = Service::createErrorParser($api->getProtocol(), $api);
277 }
278 public static function _apply_endpoint_provider(callable $value, array &$args)
279 {
280 if (!isset($args['endpoint'])) {
281 $endpointPrefix = isset($args['api']['metadata']['endpointPrefix']) ? $args['api']['metadata']['endpointPrefix'] : $args['service'];
282 // Check region is a valid host label when it is being used to
283 // generate an endpoint
284 if (!self::isValidRegion($args['region'])) {
285 throw new InvalidRegionException('Region must be a valid RFC' . ' host label.');
286 }
287 $serviceEndpoints = \is_array($value) && isset($value['services'][$args['service']]['endpoints']) ? $value['services'][$args['service']]['endpoints'] : null;
288 if (isset($serviceEndpoints[$args['region']]['deprecated'])) {
289 \trigger_error("The service " . $args['service'] . "has " . " deprecated the region " . $args['region'] . ".", \E_USER_WARNING);
290 }
291 $args['region'] = \Dudlewebs\WPMCS\s3\Aws\strip_fips_pseudo_regions($args['region']);
292 // Invoke the endpoint provider and throw if it does not resolve.
293 $result = EndpointProvider::resolve($value, ['service' => $endpointPrefix, 'region' => $args['region'], 'scheme' => $args['scheme'], 'options' => self::getEndpointProviderOptions($args)]);
294 $args['endpoint'] = $result['endpoint'];
295 if (empty($args['config']['signature_version']) && isset($result['signatureVersion'])) {
296 $args['config']['signature_version'] = $result['signatureVersion'];
297 }
298 if (empty($args['config']['signing_region']) && isset($result['signingRegion'])) {
299 $args['config']['signing_region'] = $result['signingRegion'];
300 }
301 if (empty($args['config']['signing_name']) && isset($result['signingName'])) {
302 $args['config']['signing_name'] = $result['signingName'];
303 }
304 }
305 }
306 public static function _apply_endpoint_discovery($value, array &$args)
307 {
308 $args['endpoint_discovery'] = $value;
309 }
310 public static function _default_endpoint_discovery_provider(array $args)
311 {
312 return ConfigurationProvider::defaultProvider($args);
313 }
314 public static function _apply_use_fips_endpoint($value, array &$args)
315 {
316 if ($value instanceof CacheInterface) {
317 $value = UseFipsConfigProvider::defaultProvider($args);
318 }
319 if (\is_callable($value)) {
320 $value = $value();
321 }
322 if ($value instanceof PromiseInterface) {
323 $value = $value->wait();
324 }
325 if ($value instanceof UseFipsEndpointConfigurationInterface) {
326 $args['config']['use_fips_endpoint'] = $value;
327 } else {
328 // The Configuration class itself will validate other inputs
329 $args['config']['use_fips_endpoint'] = new UseFipsEndpointConfiguration($value);
330 }
331 }
332 public static function _default_use_fips_endpoint(array &$args)
333 {
334 return UseFipsConfigProvider::defaultProvider($args);
335 }
336 public static function _apply_use_dual_stack_endpoint($value, array &$args)
337 {
338 if ($value instanceof CacheInterface) {
339 $value = UseDualStackConfigProvider::defaultProvider($args);
340 }
341 if (\is_callable($value)) {
342 $value = $value();
343 }
344 if ($value instanceof PromiseInterface) {
345 $value = $value->wait();
346 }
347 if ($value instanceof UseDualStackEndpointConfigurationInterface) {
348 $args['config']['use_dual_stack_endpoint'] = $value;
349 } else {
350 // The Configuration class itself will validate other inputs
351 $args['config']['use_dual_stack_endpoint'] = new UseDualStackEndpointConfiguration($value, $args['region']);
352 }
353 }
354 public static function _default_use_dual_stack_endpoint(array &$args)
355 {
356 return UseDualStackConfigProvider::defaultProvider($args);
357 }
358 public static function _apply_serializer($value, array &$args, HandlerList $list)
359 {
360 $list->prependBuild(Middleware::requestBuilder($value), 'builder');
361 }
362 public static function _apply_debug($value, array &$args, HandlerList $list)
363 {
364 if ($value !== \false) {
365 $list->interpose(new TraceMiddleware($value === \true ? [] : $value, $args['api']));
366 }
367 }
368 public static function _apply_stats($value, array &$args, HandlerList $list)
369 {
370 // Create an array of stat collectors that are disabled (set to false)
371 // by default. If the user has passed in true, enable all stat
372 // collectors.
373 $defaults = \array_fill_keys(['http', 'retries', 'timer'], $value === \true);
374 $args['stats'] = \is_array($value) ? \array_replace($defaults, $value) : $defaults;
375 if ($args['stats']['timer']) {
376 $list->prependInit(Middleware::timer(), 'timer');
377 }
378 }
379 public static function _apply_profile($_, array &$args)
380 {
381 $args['credentials'] = CredentialProvider::ini($args['profile']);
382 }
383 public static function _apply_validate($value, array &$args, HandlerList $list)
384 {
385 if ($value === \false) {
386 return;
387 }
388 $validator = $value === \true ? new Validator() : new Validator($value);
389 $list->appendValidate(Middleware::validation($args['api'], $validator), 'validation');
390 }
391 public static function _apply_handler($value, array &$args, HandlerList $list)
392 {
393 $list->setHandler($value);
394 }
395 public static function _default_handler(array &$args)
396 {
397 return new WrappedHttpHandler(default_http_handler(), $args['parser'], $args['error_parser'], $args['exception_class'], $args['stats']['http']);
398 }
399 public static function _apply_http_handler($value, array &$args, HandlerList $list)
400 {
401 $args['handler'] = new WrappedHttpHandler($value, $args['parser'], $args['error_parser'], $args['exception_class'], $args['stats']['http']);
402 }
403 public static function _apply_user_agent($inputUserAgent, array &$args, HandlerList $list)
404 {
405 //Add SDK version
406 $userAgent = ['aws-sdk-php/' . Sdk::VERSION];
407 //If on HHVM add the HHVM version
408 if (\defined('Dudlewebs\\WPMCS\\s3\\HHVM_VERSION')) {
409 $userAgent[] = 'HHVM/' . HHVM_VERSION;
410 }
411 //Add OS version
412 $disabledFunctions = \explode(',', \ini_get('disable_functions'));
413 if (\function_exists('php_uname') && !\in_array('php_uname', $disabledFunctions, \true)) {
414 $osName = "OS/" . \php_uname('s') . '/' . \php_uname('r');
415 if (!empty($osName)) {
416 $userAgent[] = $osName;
417 }
418 }
419 //Add the language version
420 $userAgent[] = 'lang/php/' . \phpversion();
421 //Add exec environment if present
422 if ($executionEnvironment = \getenv('AWS_EXECUTION_ENV')) {
423 $userAgent[] = $executionEnvironment;
424 }
425 //Add the input to the end
426 if ($inputUserAgent) {
427 if (!\is_array($inputUserAgent)) {
428 $inputUserAgent = [$inputUserAgent];
429 }
430 $inputUserAgent = \array_map('strval', $inputUserAgent);
431 $userAgent = \array_merge($userAgent, $inputUserAgent);
432 }
433 $args['ua_append'] = $userAgent;
434 $list->appendBuild(static function (callable $handler) use($userAgent) {
435 return function (CommandInterface $command, RequestInterface $request) use($handler, $userAgent) {
436 return $handler($command, $request->withHeader('X-Amz-User-Agent', \implode(' ', \array_merge($userAgent, $request->getHeader('X-Amz-User-Agent'))))->withHeader('User-Agent', \implode(' ', \array_merge($userAgent, $request->getHeader('User-Agent')))));
437 };
438 });
439 }
440 public static function _apply_endpoint($value, array &$args, HandlerList $list)
441 {
442 $args['endpoint'] = $value;
443 }
444 public static function _apply_idempotency_auto_fill($value, array &$args, HandlerList $list)
445 {
446 $enabled = \false;
447 $generator = null;
448 if (\is_bool($value)) {
449 $enabled = $value;
450 } elseif (\is_callable($value)) {
451 $enabled = \true;
452 $generator = $value;
453 }
454 if ($enabled) {
455 $list->prependInit(IdempotencyTokenMiddleware::wrap($args['api'], $generator), 'idempotency_auto_fill');
456 }
457 }
458 public static function _default_endpoint_provider(array $args)
459 {
460 $options = self::getEndpointProviderOptions($args);
461 return PartitionEndpointProvider::defaultProvider($options)->getPartition($args['region'], $args['service']);
462 }
463 public static function _default_serializer(array $args)
464 {
465 return Service::createSerializer($args['api'], $args['endpoint']);
466 }
467 public static function _default_signature_provider()
468 {
469 return SignatureProvider::defaultProvider();
470 }
471 public static function _default_signature_version(array &$args)
472 {
473 if (isset($args['config']['signature_version'])) {
474 return $args['config']['signature_version'];
475 }
476 $args['__partition_result'] = isset($args['__partition_result']) ? isset($args['__partition_result']) : \call_user_func(PartitionEndpointProvider::defaultProvider(), ['service' => $args['service'], 'region' => $args['region']]);
477 return isset($args['__partition_result']['signatureVersion']) ? $args['__partition_result']['signatureVersion'] : $args['api']->getSignatureVersion();
478 }
479 public static function _default_signing_name(array &$args)
480 {
481 if (isset($args['config']['signing_name'])) {
482 return $args['config']['signing_name'];
483 }
484 $args['__partition_result'] = isset($args['__partition_result']) ? isset($args['__partition_result']) : \call_user_func(PartitionEndpointProvider::defaultProvider(), ['service' => $args['service'], 'region' => $args['region']]);
485 if (isset($args['__partition_result']['signingName'])) {
486 return $args['__partition_result']['signingName'];
487 }
488 if ($signingName = $args['api']->getSigningName()) {
489 return $signingName;
490 }
491 return $args['service'];
492 }
493 public static function _default_signing_region(array &$args)
494 {
495 if (isset($args['config']['signing_region'])) {
496 return $args['config']['signing_region'];
497 }
498 $args['__partition_result'] = isset($args['__partition_result']) ? isset($args['__partition_result']) : \call_user_func(PartitionEndpointProvider::defaultProvider(), ['service' => $args['service'], 'region' => $args['region']]);
499 return isset($args['__partition_result']['signingRegion']) ? $args['__partition_result']['signingRegion'] : $args['region'];
500 }
501 public static function _missing_version(array $args)
502 {
503 $service = isset($args['service']) ? $args['service'] : '';
504 $versions = ApiProvider::defaultProvider()->getVersions($service);
505 $versions = \implode("\n", \array_map(function ($v) {
506 return "* \"{$v}\"";
507 }, $versions)) ?: '* (none found)';
508 return <<<EOT
509 A "version" configuration value is required. Specifying a version constraint
510 ensures that your code will not be affected by a breaking change made to the
511 service. For example, when using Amazon S3, you can lock your API version to
512 "2006-03-01".
513
514 Your build of the SDK has the following version(s) of "{$service}": {$versions}
515
516 You may provide "latest" to the "version" configuration value to utilize the
517 most recent available API version that your client's API provider can find.
518 Note: Using 'latest' in a production application is not recommended.
519
520 A list of available API versions can be found on each client's API documentation
521 page: http://docs.aws.amazon.com/aws-sdk-php/v3/api/index.html. If you are
522 unable to load a specific API version, then you may need to update your copy of
523 the SDK.
524 EOT;
525 }
526 public static function _missing_region(array $args)
527 {
528 $service = isset($args['service']) ? $args['service'] : '';
529 return <<<EOT
530 A "region" configuration value is required for the "{$service}" service
531 (e.g., "us-west-2"). A list of available public regions and endpoints can be
532 found at http://docs.aws.amazon.com/general/latest/gr/rande.html.
533 EOT;
534 }
535 /**
536 * Extracts client options for the endpoint provider to its own array
537 *
538 * @param array $args
539 * @return array
540 */
541 private static function getEndpointProviderOptions(array $args)
542 {
543 $options = [];
544 $optionKeys = ['sts_regional_endpoints', 's3_us_east_1_regional_endpoint'];
545 $configKeys = ['use_dual_stack_endpoint', 'use_fips_endpoint'];
546 foreach ($optionKeys as $key) {
547 if (isset($args[$key])) {
548 $options[$key] = $args[$key];
549 }
550 }
551 foreach ($configKeys as $key) {
552 if (isset($args['config'][$key])) {
553 $options[$key] = $args['config'][$key];
554 }
555 }
556 return $options;
557 }
558 /**
559 * Validates a region to be used for endpoint construction
560 *
561 * @param $region
562 * @return bool
563 */
564 private static function isValidRegion($region)
565 {
566 return is_valid_hostlabel($region);
567 }
568 }
569