|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Ely\Mojang\Middleware; |
|
5
|
|
|
|
|
6
|
|
|
use Ely\Mojang\Exception; |
|
7
|
|
|
use GuzzleHttp\Promise\PromiseInterface; |
|
8
|
|
|
use Psr\Http\Message\RequestInterface; |
|
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
10
|
|
|
|
|
11
|
|
|
class ResponseConverterMiddleware { |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* @var callable |
|
15
|
|
|
*/ |
|
16
|
|
|
private $nextHandler; |
|
17
|
|
|
|
|
18
|
38 |
|
public function __construct(callable $nextHandler) { |
|
19
|
38 |
|
$this->nextHandler = $nextHandler; |
|
20
|
38 |
|
} |
|
21
|
|
|
|
|
22
|
38 |
|
public function __invoke(RequestInterface $request, array $options): PromiseInterface { |
|
23
|
38 |
|
$fn = $this->nextHandler; |
|
24
|
|
|
/** @var PromiseInterface $promise */ |
|
25
|
38 |
|
$promise = $fn($request, $options); |
|
26
|
|
|
|
|
27
|
|
|
return $promise->then(static function($response) use ($request) { |
|
28
|
38 |
|
if ($response instanceof ResponseInterface) { |
|
29
|
38 |
|
$method = $request->getMethod(); |
|
30
|
38 |
|
$statusCode = $response->getStatusCode(); |
|
31
|
38 |
|
if ($method === 'GET' && $statusCode === 204) { |
|
32
|
3 |
|
throw new Exception\NoContentException($request, $response); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
35 |
|
if ($statusCode === 403) { |
|
36
|
5 |
|
throw new Exception\ForbiddenException($request, $response); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
30 |
|
if ($statusCode === 429) { |
|
40
|
1 |
|
throw new Exception\TooManyRequestsException($request, $response); |
|
41
|
|
|
} |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
29 |
|
return $response; |
|
45
|
38 |
|
}); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
37 |
|
public static function create(): callable { |
|
49
|
|
|
return static function(callable $handler): callable { |
|
50
|
35 |
|
return new static($handler); |
|
51
|
37 |
|
}; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
} |
|
55
|
|
|
|