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 / WrappedHttpHandler.php

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

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