1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace ApiClients\Client\Github\Middleware; |
4
|
|
|
|
5
|
|
|
use ApiClients\Client\Github\ApiErrorException; |
6
|
|
|
use ApiClients\Foundation\Middleware\Annotation\SecondLast; |
7
|
|
|
use ApiClients\Foundation\Middleware\MiddlewareInterface; |
8
|
|
|
use ApiClients\Foundation\Middleware\PostTrait; |
9
|
|
|
use ApiClients\Foundation\Middleware\PreTrait; |
10
|
|
|
use ApiClients\Foundation\Transport\ParsedContentsInterface; |
11
|
|
|
use ApiClients\Tools\Psr7\HttpStatusExceptions\BadRequestException; |
12
|
|
|
use ApiClients\Tools\Psr7\HttpStatusExceptions\UnprocessableEntityException; |
13
|
|
|
use React\Promise\CancellablePromiseInterface; |
14
|
|
|
use function React\Promise\reject; |
15
|
|
|
use Throwable; |
16
|
|
|
|
17
|
|
|
final class ErrorMiddleware implements MiddlewareInterface |
18
|
|
|
{ |
19
|
|
|
use PreTrait; |
20
|
|
|
use PostTrait; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param Throwable $throwable |
24
|
|
|
* @param string $transactionId |
25
|
|
|
* @param array $options |
26
|
|
|
* @return CancellablePromiseInterface |
27
|
|
|
* @SecondLast() |
28
|
|
|
*/ |
29
|
|
|
public function error( |
30
|
|
|
Throwable $throwable, |
31
|
|
|
string $transactionId, |
32
|
|
|
array $options = [] |
33
|
|
|
): CancellablePromiseInterface { |
34
|
|
|
if ($throwable instanceof UnprocessableEntityException || |
35
|
|
|
$throwable instanceof BadRequestException |
36
|
|
|
) { |
37
|
|
|
$response = $throwable->getResponse(); |
38
|
|
|
$body = $response->getBody(); |
39
|
|
|
if (!($body instanceof ParsedContentsInterface)) { |
40
|
|
|
return reject($throwable); |
41
|
|
|
} |
42
|
|
|
$contents = $body->getParsedContents(); |
43
|
|
|
$message = $contents['message'] ?? $throwable->getMessage(); |
44
|
|
|
|
45
|
|
|
if (isset($contents['errors'])) { |
46
|
|
|
return reject( |
47
|
|
|
ApiErrorException::createWithErrors( |
48
|
|
|
$message, |
49
|
|
|
$throwable->getCode(), |
50
|
|
|
$contents['errors'], |
51
|
|
|
$throwable |
52
|
|
|
) |
53
|
|
|
); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return reject( |
57
|
|
|
ApiErrorException::create( |
58
|
|
|
$message, |
59
|
|
|
$throwable->getCode(), |
60
|
|
|
$throwable |
61
|
|
|
) |
62
|
|
|
); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return reject($throwable); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|