Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/functions.php

raw symbols SCIP
1 <?php
2 namespace Aws;
3
4 use GuzzleHttp\Utils;
5 use Psr\Http\Message\RequestInterface;
6 use GuzzleHttp\Promise\FulfilledPromise;
7
8 //-----------------------------------------------------------------------------
9 // Functional functions
10 //-----------------------------------------------------------------------------
11
12 /**
13 * Returns a function that always returns the same value;
14 *
15 * @param mixed $value Value to return.
16 *
17 * @return callable
18 */
19 function constantly($value)
20 {
21 return function () use ($value) { return $value; };
22 }
23
24 /**
25 * Filters values that do not satisfy the predicate function $pred.
26 *
27 * @param mixed $iterable Iterable sequence of data.
28 * @param callable $pred Function that accepts a value and returns true/false
29 *
30 * @return \Generator
31 */
32 function filter($iterable, callable $pred)
33 {
34 foreach ($iterable as $value) {
35 if ($pred($value)) {
36 yield $value;
37 }
38 }
39 }
40
41 /**
42 * Applies a map function $f to each value in a collection.
43 *
44 * @param mixed $iterable Iterable sequence of data.
45 * @param callable $f Map function to apply.
46 *
47 * @return \Generator
48 */
49 function map($iterable, callable $f)
50 {
51 foreach ($iterable as $value) {
52 yield $f($value);
53 }
54 }
55
56 /**
57 * Creates a generator that iterates over a sequence, then iterates over each
58 * value in the sequence and yields the application of the map function to each
59 * value.
60 *
61 * @param mixed $iterable Iterable sequence of data.
62 * @param callable $f Map function to apply.
63 *
64 * @return \Generator
65 */
66 function flatmap($iterable, callable $f)
67 {
68 foreach (map($iterable, $f) as $outer) {
69 foreach ($outer as $inner) {
70 yield $inner;
71 }
72 }
73 }
74
75 /**
76 * Partitions the input sequence into partitions of the specified size.
77 *
78 * @param mixed $iterable Iterable sequence of data.
79 * @param int $size Size to make each partition (except possibly the last chunk)
80 *
81 * @return \Generator
82 */
83 function partition($iterable, $size)
84 {
85 $buffer = [];
86 foreach ($iterable as $value) {
87 $buffer[] = $value;
88 if (count($buffer) === $size) {
89 yield $buffer;
90 $buffer = [];
91 }
92 }
93
94 if ($buffer) {
95 yield $buffer;
96 }
97 }
98
99 /**
100 * Returns a function that invokes the provided variadic functions one
101 * after the other until one of the functions returns a non-null value.
102 * The return function will call each passed function with any arguments it
103 * is provided.
104 *
105 * $a = function ($x, $y) { return null; };
106 * $b = function ($x, $y) { return $x + $y; };
107 * $fn = \Aws\or_chain($a, $b);
108 * echo $fn(1, 2); // 3
109 *
110 * @return callable
111 */
112 function or_chain()
113 {
114 $fns = func_get_args();
115 return function () use ($fns) {
116 $args = func_get_args();
117 foreach ($fns as $fn) {
118 $result = $args ? call_user_func_array($fn, $args) : $fn();
119 if ($result) {
120 return $result;
121 }
122 }
123 return null;
124 };
125 }
126
127 //-----------------------------------------------------------------------------
128 // JSON compiler and loading functions
129 //-----------------------------------------------------------------------------
130
131 /**
132 * Loads a compiled JSON file from a PHP file.
133 *
134 * If the JSON file has not been cached to disk as a PHP file, it will be loaded
135 * from the JSON source file and returned.
136 *
137 * @param string $path Path to the JSON file on disk
138 *
139 * @return mixed Returns the JSON decoded data. Note that JSON objects are
140 * decoded as associative arrays.
141 */
142 function load_compiled_json($path)
143 {
144 static $compiledList = [];
145
146 $compiledFilepath = "{$path}.php";
147
148 if (!isset($compiledList[$compiledFilepath])) {
149 if (is_readable($compiledFilepath)) {
150 $compiledList[$compiledFilepath] = include($compiledFilepath);
151 }
152 }
153
154 if (isset($compiledList[$compiledFilepath])) {
155 return $compiledList[$compiledFilepath];
156 }
157
158 if (!file_exists($path)) {
159 throw new \InvalidArgumentException(
160 sprintf("File not found: %s", $path)
161 );
162 }
163
164 return json_decode(file_get_contents($path), true);
165 }
166
167 /**
168 * No-op
169 */
170 function clear_compiled_json()
171 {
172 // pass
173 }
174
175 //-----------------------------------------------------------------------------
176 // Directory iterator functions.
177 //-----------------------------------------------------------------------------
178
179 /**
180 * Iterates over the files in a directory and works with custom wrappers.
181 *
182 * @param string $path Path to open (e.g., "s3://foo/bar").
183 * @param resource $context Stream wrapper context.
184 *
185 * @return \Generator Yields relative filename strings.
186 */
187 function dir_iterator($path, $context = null)
188 {
189 $dh = $context ? opendir($path, $context) : opendir($path);
190 if (!$dh) {
191 throw new \InvalidArgumentException('File not found: ' . $path);
192 }
193 while (($file = readdir($dh)) !== false) {
194 yield $file;
195 }
196 closedir($dh);
197 }
198
199 /**
200 * Returns a recursive directory iterator that yields absolute filenames.
201 *
202 * This iterator is not broken like PHP's built-in DirectoryIterator (which
203 * will read the first file from a stream wrapper, then rewind, then read
204 * it again).
205 *
206 * @param string $path Path to traverse (e.g., s3://bucket/key, /tmp)
207 * @param resource $context Stream context options.
208 *
209 * @return \Generator Yields absolute filenames.
210 */
211 function recursive_dir_iterator($path, $context = null)
212 {
213 $invalid = ['.' => true, '..' => true];
214 $pathLen = strlen($path) + 1;
215 $iterator = dir_iterator($path, $context);
216 $queue = [];
217 do {
218 while ($iterator->valid()) {
219 $file = $iterator->current();
220 $iterator->next();
221 if (isset($invalid[basename($file)])) {
222 continue;
223 }
224 $fullPath = "{$path}/{$file}";
225 yield $fullPath;
226 if (is_dir($fullPath)) {
227 $queue[] = $iterator;
228 $iterator = map(
229 dir_iterator($fullPath, $context),
230 function ($file) use ($fullPath, $pathLen) {
231 return substr("{$fullPath}/{$file}", $pathLen);
232 }
233 );
234 continue;
235 }
236 }
237 $iterator = array_pop($queue);
238 } while ($iterator);
239 }
240
241 //-----------------------------------------------------------------------------
242 // Misc. functions.
243 //-----------------------------------------------------------------------------
244
245 /**
246 * Debug function used to describe the provided value type and class.
247 *
248 * @param mixed $input
249 *
250 * @return string Returns a string containing the type of the variable and
251 * if a class is provided, the class name.
252 */
253 function describe_type($input)
254 {
255 switch (gettype($input)) {
256 case 'object':
257 return 'object(' . get_class($input) . ')';
258 case 'array':
259 return 'array(' . count($input) . ')';
260 default:
261 ob_start();
262 var_dump($input);
263 // normalize float vs double
264 return str_replace('double(', 'float(', rtrim(ob_get_clean()));
265 }
266 }
267
268 /**
269 * Creates a default HTTP handler based on the available clients.
270 *
271 * @return callable
272 */
273 function default_http_handler()
274 {
275 return new \Aws\Handler\Guzzle\GuzzleHandler();
276 }
277
278 /**
279 * Gets the default user agent string depending on the Guzzle version
280 *
281 * @return string
282 */
283 function default_user_agent()
284 {
285 return Utils::defaultUserAgent();
286 }
287
288 /**
289 * Serialize a request for a command but do not send it.
290 *
291 * Returns a promise that is fulfilled with the serialized request.
292 *
293 * @param CommandInterface $command Command to serialize.
294 *
295 * @return RequestInterface
296 * @throws \RuntimeException
297 */
298 function serialize(CommandInterface $command)
299 {
300 $request = null;
301 $handlerList = $command->getHandlerList();
302
303 // Return a mock result.
304 $handlerList->setHandler(
305 function (CommandInterface $_, RequestInterface $r) use (&$request) {
306 $request = $r;
307 return new FulfilledPromise(new Result([]));
308 }
309 );
310
311 call_user_func($handlerList->resolve(), $command)->wait();
312 if (!$request instanceof RequestInterface) {
313 throw new \RuntimeException(
314 'Calling handler did not serialize request'
315 );
316 }
317
318 return $request;
319 }
320
321 /**
322 * Retrieves data for a service from the SDK's service manifest file.
323 *
324 * Manifest data is stored statically, so it does not need to be loaded more
325 * than once per process. The JSON data is also cached in opcache.
326 *
327 * @param string $service Case-insensitive namespace or endpoint prefix of the
328 * service for which you are retrieving manifest data.
329 *
330 * @return array
331 * @throws \InvalidArgumentException if the service is not supported.
332 */
333 function manifest($service = null)
334 {
335 // Load the manifest and create aliases for lowercased namespaces
336 static $manifest = [];
337 static $aliases = [];
338 if (empty($manifest)) {
339 $manifest = load_compiled_json(__DIR__ . '/data/manifest.json');
340 foreach ($manifest as $endpoint => $info) {
341 $alias = strtolower($info['namespace']);
342 if ($alias !== $endpoint) {
343 $aliases[$alias] = $endpoint;
344 }
345 }
346 }
347
348 // If no service specified, then return the whole manifest.
349 if ($service === null) {
350 return $manifest;
351 }
352
353 // Look up the service's info in the manifest data.
354 $service = strtolower($service);
355 if (isset($manifest[$service])) {
356 return $manifest[$service] + ['endpoint' => $service];
357 }
358
359 if (isset($aliases[$service])) {
360 return manifest($aliases[$service]);
361 }
362
363 throw new \InvalidArgumentException(
364 "The service \"{$service}\" is not provided by the AWS SDK for PHP."
365 );
366 }
367
368 /**
369 * Checks if supplied parameter is a valid hostname
370 *
371 * @param string $hostname
372 * @return bool
373 */
374 function is_valid_hostname($hostname)
375 {
376 return (
377 preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*\.?$/i", $hostname)
378 && preg_match("/^.{1,253}$/", $hostname)
379 && preg_match("/^[^\.]{1,63}(\.[^\.]{0,63})*$/", $hostname)
380 );
381 }
382
383 /**
384 * Checks if supplied parameter is a valid host label
385 *
386 * @param $label
387 * @return bool
388 */
389 function is_valid_hostlabel($label)
390 {
391 return preg_match("/^(?!-)[a-zA-Z0-9-]{1,63}(?<!-)$/", $label);
392 }
393
394 /**
395 * Ignores '#' full line comments, which parse_ini_file no longer does
396 * in PHP 7+.
397 *
398 * @param $filename
399 * @param bool $process_sections
400 * @param int $scanner_mode
401 * @return array|bool
402 */
403 function parse_ini_file(
404 $filename,
405 $process_sections = false,
406 $scanner_mode = INI_SCANNER_NORMAL)
407 {
408 return parse_ini_string(
409 preg_replace('/^#.*\\n/m', "", file_get_contents($filename)),
410 $process_sections,
411 $scanner_mode
412 );
413 }
414
415 /**
416 * Outputs boolean value of input for a select range of possible values,
417 * null otherwise
418 *
419 * @param $input
420 * @return bool|null
421 */
422 function boolean_value($input)
423 {
424 if (is_bool($input)) {
425 return $input;
426 }
427
428 if ($input === 0) {
429 return false;
430 }
431
432 if ($input === 1) {
433 return true;
434 }
435
436 if (is_string($input)) {
437 switch (strtolower($input)) {
438 case "true":
439 case "on":
440 case "1":
441 return true;
442 break;
443
444 case "false":
445 case "off":
446 case "0":
447 return false;
448 break;
449 }
450 }
451 return null;
452 }
453
454 /**
455 * Parses ini sections with subsections (i.e. the service section)
456 *
457 * @param $filename
458 * @param $filename
459 * @return array
460 */
461 function parse_ini_section_with_subsections($filename, $section_name) {
462 $config = [];
463 $stream = fopen($filename, 'r');
464
465 if (!$stream) {
466 return $config;
467 }
468
469 $current_subsection = '';
470
471 while (!feof($stream)) {
472 $line = trim(fgets($stream));
473
474 if (empty($line) || in_array($line[0], [';', '#'])) {
475 continue;
476 }
477
478 if (preg_match('/^\[.*\]$/', $line)
479 && trim($line, '[]') === $section_name)
480 {
481 while (!feof($stream)) {
482 $line = trim(fgets($stream));
483
484 if (empty($line) || in_array($line[0], [';', '#'])) {
485 continue;
486 }
487
488 if (preg_match('/^\[.*\]$/', $line)
489 && trim($line, '[]') === $section_name)
490 {
491 continue;
492 } elseif (strpos($line, '[') === 0) {
493 break;
494 }
495
496 if (strpos($line, ' = ') !== false) {
497 list($key, $value) = explode(' = ', $line, 2);
498 if (empty($current_subsection)) {
499 $config[$key] = $value;
500 } else {
501 $config[$current_subsection][$key] = $value;
502 }
503 } else {
504 $current_subsection = trim(str_replace('=', '', $line));
505 $config[$current_subsection] = [];
506 }
507 }
508 }
509 }
510
511 fclose($stream);
512 return $config;
513 }
514
515 /**
516 * Checks if an input is a valid epoch time
517 *
518 * @param $input
519 * @return bool
520 */
521 function is_valid_epoch($input)
522 {
523 if (is_string($input) || is_numeric($input)) {
524 if (is_string($input) && !preg_match("/^-?[0-9]+\.?[0-9]*$/", $input)) {
525 return false;
526 }
527 return true;
528 }
529 return false;
530 }
531
532 /**
533 * Checks if an input is a fips pseudo region
534 *
535 * @param $region
536 * @return bool
537 */
538 function is_fips_pseudo_region($region)
539 {
540 return strpos($region, 'fips-') !== false || strpos($region, '-fips') !== false;
541 }
542
543 /**
544 * Returns a region without a fips label
545 *
546 * @param $region
547 * @return string
548 */
549 function strip_fips_pseudo_regions($region)
550 {
551 return str_replace(['fips-', '-fips'], ['', ''], $region);
552 }
553
554 /**
555 * Checks if an array is associative
556 *
557 * @param array $array
558 *
559 * @return bool
560 */
561 function is_associative(array $array): bool
562 {
563 if (empty($array)) {
564 return false;
565 }
566
567 return !array_is_list($array);
568 }