PluginProbe
Media Cloud Sync / 1.3.11
Media Cloud Sync v1.3.11
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 / WrappedHttpHandler.php

WrappedHttpHandler.php in Media Cloud Sync 1.3.11, at includes/sdk/s3/Aws/WrappedHttpHandler.php

143 lines 6.3 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\Parser\Exception\ParserException;
6 use Dudlewebs\WPMCS\s3\Aws\Exception\AwsException;
7 use Dudlewebs\WPMCS\s3\GuzzleHttp\Promise;
8 use Dudlewebs\WPMCS\s3\Psr\Http\Message\RequestInterface;
9 use Dudlewebs\WPMCS\s3\Psr\Http\Message\ResponseInterface;
10 /**
11 * Converts an HTTP handler into a Command HTTP handler.
12 *
13 * HTTP handlers have the following signature:
14 * function(RequestInterface $request, array $options) : PromiseInterface
15 *
16 * The promise returned form an HTTP handler must resolve to a PSR-7 response
17 * object when fulfilled or an error array when rejected. The error array
18 * can contain the following data:
19 *
20 * - exception: (required, Exception) Exception that was encountered.
21 * - response: (ResponseInterface) PSR-7 response that was received (if a
22 * response) was received.
23 * - connection_error: (bool) True if the error is the result of failing to
24 * connect.
25 */
26 class WrappedHttpHandler
27 {
28 private $httpHandler;
29 private $parser;
30 private $errorParser;
31 private $exceptionClass;
32 private $collectStats;
33 /**
34 * @param callable $httpHandler Function that accepts a request and array
35 * of request options and returns a promise
36 * that fulfills with a response or rejects
37 * with an error array.
38 * @param callable $parser Function that accepts a response object
39 * and returns an AWS result object.
40 * @param callable $errorParser Function that parses a response object
41 * into AWS error data.
42 * @param string $exceptionClass Exception class to throw.
43 * @param bool $collectStats Whether to collect HTTP transfer
44 * information.
45 */
46 public function __construct(callable $httpHandler, callable $parser, callable $errorParser, $exceptionClass = AwsException::class, $collectStats = \false)
47 {
48 $this->httpHandler = $httpHandler;
49 $this->parser = $parser;
50 $this->errorParser = $errorParser;
51 $this->exceptionClass = $exceptionClass;
52 $this->collectStats = $collectStats;
53 }
54 /**
55 * Calls the simpler HTTP specific handler and wraps the returned promise
56 * with AWS specific values (e.g., a result object or AWS exception).
57 *
58 * @param CommandInterface $command Command being executed.
59 * @param RequestInterface $request Request to send.
60 *
61 * @return Promise\PromiseInterface
62 */
63 public function __invoke(CommandInterface $command, RequestInterface $request)
64 {
65 $fn = $this->httpHandler;
66 $options = $command['@http'] ?: [];
67 $stats = [];
68 if ($this->collectStats || !empty($options['collect_stats'])) {
69 $options['http_stats_receiver'] = static function (array $transferStats) use(&$stats) {
70 $stats = $transferStats;
71 };
72 } elseif (isset($options['http_stats_receiver'])) {
73 throw new \InvalidArgumentException('Providing a custom HTTP stats' . ' receiver to Aws\\WrappedHttpHandler is not supported.');
74 }
75 return Promise\Create::promiseFor($fn($request, $options))->then(function (ResponseInterface $res) use($command, $request, &$stats) {
76 return $this->parseResponse($command, $request, $res, $stats);
77 }, function ($err) use($request, $command, &$stats) {
78 if (\is_array($err)) {
79 $err = $this->parseError($err, $request, $command, $stats);
80 }
81 return new Promise\RejectedPromise($err);
82 });
83 }
84 /**
85 * @param CommandInterface $command
86 * @param RequestInterface $request
87 * @param ResponseInterface $response
88 * @param array $stats
89 *
90 * @return ResultInterface
91 */
92 private function parseResponse(CommandInterface $command, RequestInterface $request, ResponseInterface $response, array $stats)
93 {
94 $parser = $this->parser;
95 $status = $response->getStatusCode();
96 $result = $status < 300 ? $parser($command, $response) : new Result();
97 $metadata = ['statusCode' => $status, 'effectiveUri' => (string) $request->getUri(), 'headers' => [], 'transferStats' => []];
98 if (!empty($stats)) {
99 $metadata['transferStats']['http'] = [$stats];
100 }
101 // Bring headers into the metadata array.
102 foreach ($response->getHeaders() as $name => $values) {
103 $metadata['headers'][\strtolower($name)] = $values[0];
104 }
105 $result['@metadata'] = $metadata;
106 return $result;
107 }
108 /**
109 * Parses a rejection into an AWS error.
110 *
111 * @param array $err Rejection error array.
112 * @param RequestInterface $request Request that was sent.
113 * @param CommandInterface $command Command being sent.
114 * @param array $stats Transfer statistics
115 *
116 * @return \Exception
117 */
118 private function parseError(array $err, RequestInterface $request, CommandInterface $command, array $stats)
119 {
120 if (!isset($err['exception'])) {
121 throw new \RuntimeException('The HTTP handler was rejected without an "exception" key value pair.');
122 }
123 $serviceError = "AWS HTTP error: " . $err['exception']->getMessage();
124 if (!isset($err['response'])) {
125 $parts = ['response' => null];
126 } else {
127 try {
128 $parts = \call_user_func($this->errorParser, $err['response'], $command);
129 $serviceError .= " {$parts['code']} ({$parts['type']}): " . "{$parts['message']} - " . $err['response']->getBody();
130 } catch (ParserException $e) {
131 $parts = [];
132 $serviceError .= ' Unable to parse error information from ' . "response - {$e->getMessage()}";
133 }
134 $parts['response'] = $err['response'];
135 }
136 $parts['exception'] = $err['exception'];
137 $parts['request'] = $request;
138 $parts['connection_error'] = !empty($err['connection_error']);
139 $parts['transfer_stats'] = $stats;
140 return new $this->exceptionClass(\sprintf('Error executing "%s" on "%s"; %s', $command->getName(), $request->getUri(), $serviceError), $command, $parts, $err['exception']);
141 }
142 }
143