|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Incenteev\AsyncAmazonIncentives; |
| 4 | + |
| 5 | +use AsyncAws\Core\AwsError\AwsError; |
| 6 | +use AsyncAws\Core\AwsError\AwsErrorFactoryFromResponseTrait; |
| 7 | +use AsyncAws\Core\AwsError\AwsErrorFactoryInterface; |
| 8 | +use AsyncAws\Core\Exception\RuntimeException; |
| 9 | +use AsyncAws\Core\Exception\UnexpectedValue; |
| 10 | +use AsyncAws\Core\Exception\UnparsableResponse; |
| 11 | + |
| 12 | +class AmazonIncentivesErrorFactory implements AwsErrorFactoryInterface |
| 13 | +{ |
| 14 | + use AwsErrorFactoryFromResponseTrait; |
| 15 | + |
| 16 | + public function createFromContent(string $content, array $headers): AwsError |
| 17 | + { |
| 18 | + try { |
| 19 | + set_error_handler(static function ($errno, $errstr) { |
| 20 | + throw new RuntimeException($errstr, $errno); |
| 21 | + }); |
| 22 | + |
| 23 | + try { |
| 24 | + $xml = new \SimpleXMLElement($content); |
| 25 | + } finally { |
| 26 | + restore_error_handler(); |
| 27 | + } |
| 28 | + |
| 29 | + return self::parseXml($xml); |
| 30 | + } catch (\Throwable $e) { |
| 31 | + throw new UnparsableResponse('Failed to parse AWS error: ' . $content, 0, $e); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + private static function parseXml(\SimpleXMLElement $xml): AwsError |
| 36 | + { |
| 37 | + if ('ThrottlingException' === $xml->getName() && 1 === $xml->Message->count()) { |
| 38 | + return new AwsError('ThrottlingException', $xml->Message->__toString(), null, null); |
| 39 | + } |
| 40 | + |
| 41 | + if (1 === $xml->errorType->count() && 1 === $xml->Message->count()) { |
| 42 | + return new AwsError( |
| 43 | + $xml->errorType->__toString(), |
| 44 | + $xml->Message->__toString(), |
| 45 | + null, |
| 46 | + null |
| 47 | + ); |
| 48 | + } |
| 49 | + |
| 50 | + throw new UnexpectedValue('XML does not contains AWS Error'); |
| 51 | + } |
| 52 | +} |
0 commit comments