Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/S3/Parser/S3Parser.php

raw symbols SCIP
1 <?php
2
3 namespace Aws\S3\Parser;
4
5 use Aws\Api\ErrorParser\XmlErrorParser;
6 use Aws\Api\Parser\AbstractParser;
7 use Aws\Api\Parser\Exception\ParserException;
8 use Aws\Api\Service;
9 use Aws\Api\StructureShape;
10 use Aws\CommandInterface;
11 use Aws\Exception\AwsException;
12 use Aws\ResultInterface;
13 use Psr\Http\Message\ResponseInterface;
14 use Psr\Http\Message\StreamInterface;
15
16 /**
17 * Custom S3 parser on top of the S3 protocol parser
18 * for handling specific S3 parsing scenarios.
19 *
20 * @internal
21 */
22 final class S3Parser extends AbstractParser
23 {
24 /** @var AbstractParser */
25 private $protocolParser;
26 /** @var XmlErrorParser */
27 private $errorParser;
28 /** @var string */
29 private $exceptionClass;
30 /** @var array */
31 private $s3ResultMutators;
32
33 /**
34 * @param AbstractParser $protocolParser
35 * @param XmlErrorParser $errorParser
36 * @param Service $api
37 * @param string $exceptionClass
38 */
39 public function __construct(
40 AbstractParser $protocolParser,
41 XmlErrorParser $errorParser,
42 Service $api,
43 string $exceptionClass = AwsException::class
44 )
45 {
46 parent::__construct($api);
47 $this->protocolParser = $protocolParser;
48 $this->errorParser = $errorParser;
49 $this->exceptionClass = $exceptionClass;
50 $this->s3ResultMutators = [];
51 }
52
53 /**
54 * Parses a S3 response.
55 *
56 * @param CommandInterface $command The command that originated the request.
57 * @param ResponseInterface $response The response received from the service.
58 *
59 * @return ResultInterface|null
60 */
61 public function __invoke(
62 CommandInterface $command,
63 ResponseInterface $response
64 ):? ResultInterface
65 {
66 // Check first if the response is an error
67 $this->parse200Error($command, $response);
68
69 try {
70 $parseFn = $this->protocolParser;
71 $result = $parseFn($command, $response);
72 } catch (ParserException $e) {
73 // Parsing errors will be considered retryable.
74 throw new $this->exceptionClass(
75 "Error parsing response for {$command->getName()}:"
76 . " AWS parsing error: {$e->getMessage()}",
77 $command,
78 ['connection_error' => true, 'exception' => $e],
79 $e
80 );
81 }
82
83 return $this->executeS3ResultMutators($result, $command, $response);
84 }
85
86 /**
87 * Tries to parse a 200 response as an error from S3.
88 * If the parsed result contains a code and message then that means an error
89 * was found, and hence an exception is thrown with that error.
90 *
91 * @param CommandInterface $command
92 * @param ResponseInterface $response
93 *
94 * @return void
95 */
96 private function parse200Error(
97 CommandInterface $command,
98 ResponseInterface $response
99 ): void
100 {
101 // This error parsing should be just for 200 error responses
102 // and operations where its output shape does not have a streaming
103 // member and the body of the response is seekable.
104 if (200 !== $response->getStatusCode()
105 || !$this->shouldBeConsidered200Error($command->getName())
106 || !$response->getBody()->isSeekable()) {
107 return;
108 }
109
110 // To guarantee we try the error parsing just for an Error xml response.
111 if (!$this->isFirstRootElementError($response->getBody())) {
112 return;
113 }
114
115 try {
116 $errorParserFn = $this->errorParser;
117 $parsedError = $errorParserFn($response, $command);
118 } catch (ParserException $e) {
119 // Parsing errors will be considered retryable.
120 $parsedError = [
121 'code' => 'ConnectionError',
122 'message' => "An error connecting to the service occurred"
123 . " while performing the " . $command->getName()
124 . " operation."
125 ];
126 }
127
128 if (isset($parsedError['code']) && isset($parsedError['message'])) {
129 throw new $this->exceptionClass(
130 $parsedError['message'],
131 $command,
132 [
133 'connection_error' => true,
134 'code' => $parsedError['code'],
135 'message' => $parsedError['message']
136 ]
137 );
138 }
139 }
140
141 /**
142 * Checks if a specific operation should be considered
143 * a s3 200 error. Operations where any of its output members
144 * has a streaming or httpPayload trait should be not considered.
145 *
146 * @param $commandName
147 *
148 * @return bool
149 */
150 private function shouldBeConsidered200Error($commandName): bool
151 {
152 $operation = $this->api->getOperation($commandName);
153 $output = $operation->getOutput();
154 foreach ($output->getMembers() as $_ => $memberProps) {
155 if (!empty($memberProps['eventstream']) || !empty($memberProps['streaming'])) {
156 return false;
157 }
158 }
159
160 return true;
161 }
162
163 /**
164 * Checks if the root element of the response body is "Error", which is
165 * when we should try to parse an error from a 200 response from s3.
166 * It is recommended to make sure the stream given is seekable, otherwise
167 * the rewind call will cause a user warning.
168 *
169 * @param StreamInterface $responseBody
170 *
171 * @return bool
172 */
173 private function isFirstRootElementError(StreamInterface $responseBody): bool
174 {
175 static $pattern = '/<\?xml version="1\.0" encoding="UTF-8"\?>\s*<Error>/';
176 // To avoid performance overhead in large streams
177 $reducedBodyContent = $responseBody->read(64);
178 $foundErrorElement = preg_match($pattern, $reducedBodyContent);
179 // A rewind is needed because the stream is partially or entirely consumed
180 // in the previous read operation.
181 $responseBody->rewind();
182
183 return $foundErrorElement;
184 }
185
186 /**
187 * Execute mutator implementations over a result.
188 * Mutators are logics that modifies a result.
189 *
190 * @param ResultInterface $result
191 * @param CommandInterface $command
192 * @param ResponseInterface $response
193 *
194 * @return ResultInterface
195 */
196 private function executeS3ResultMutators(
197 ResultInterface $result,
198 CommandInterface $command,
199 ResponseInterface $response
200 ): ResultInterface
201 {
202 foreach ($this->s3ResultMutators as $mutator) {
203 $result = $mutator($result, $command, $response);
204 }
205
206 return $result;
207 }
208
209 /**
210 * Adds a mutator into the list of mutators.
211 *
212 * @param string $mutatorName
213 * @param S3ResultMutator $s3ResultMutator
214 * @return void
215 */
216 public function addS3ResultMutator(
217 string $mutatorName,
218 S3ResultMutator $s3ResultMutator
219 ): void
220 {
221 if (isset($this->s3ResultMutators[$mutatorName])) {
222 trigger_error(
223 "The S3 Result Mutator {$mutatorName} already exists!",
224 E_USER_WARNING
225 );
226
227 return;
228 }
229
230 $this->s3ResultMutators[$mutatorName] = $s3ResultMutator;
231 }
232
233 /**
234 * Removes a mutator from the mutator list.
235 *
236 * @param string $mutatorName
237 * @return void
238 */
239 public function removeS3ResultMutator(string $mutatorName): void
240 {
241 if (!isset($this->s3ResultMutators[$mutatorName])) {
242 trigger_error(
243 "The S3 Result Mutator {$mutatorName} does not exist!",
244 E_USER_WARNING
245 );
246
247 return;
248 }
249
250 unset($this->s3ResultMutators[$mutatorName]);
251 }
252
253 /**
254 * Returns the list of result mutators available.
255 *
256 * @return array
257 */
258 public function getS3ResultMutators(): array
259 {
260 return $this->s3ResultMutators;
261 }
262
263 public function parseMemberFromStream(
264 StreamInterface $stream,
265 StructureShape $member,
266 $response
267 )
268 {
269 return $this->protocolParser->parseMemberFromStream(
270 $stream,
271 $member,
272 $response
273 );
274 }
275 }