-
Notifications
You must be signed in to change notification settings - Fork 2
/
ResponseHandlerMiddleware.php
69 lines (61 loc) · 1.83 KB
/
ResponseHandlerMiddleware.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
namespace Tustin\Haste\Http\Middleware;
use GuzzleHttp\Psr7\Response;
use Tustin\Haste\Http\JsonStream;
use Psr\Http\Message\StreamInterface;
use Tustin\Haste\Exception\ApiException;
use Tustin\Haste\Exception\NotFoundHttpException;
use Tustin\Haste\Exception\AccessDeniedHttpException;
use Tustin\Haste\Exception\UnauthorizedHttpException;
use Tustin\Haste\Exception\UnsupportedMediaTypeHttpException;
final class ResponseHandlerMiddleware
{
/**
* Handles all responses.
*
* @param Response $response
* @param array $options
* @return void
*/
public function __invoke($response, $options = [])
{
$jsonStream = new JsonStream($response->getBody());
if ($this->isSuccessful($response)) {
return $response->withBody($jsonStream);
}
$this->handleErrorResponse($response, $jsonStream);
}
/**
* Checks if the HTTP status code is successful.
*
* @param Response $response
* @return bool
*/
public function isSuccessful(Response $response): bool
{
return $response->getStatusCode() < 400;
}
/**
* Handles unsuccessful error codes by throwing the proper exception.
*
* @param Response $response
* @param StreamInterface $stream
*
* @return void
*/
public function handleErrorResponse(Response $response, StreamInterface $stream): void
{
switch ($response->getStatusCode()) {
case 400:
throw new ApiException($stream);
case 401:
throw new UnauthorizedHttpException;
case 403:
throw new AccessDeniedHttpException;
case 404:
throw new NotFoundHttpException;
case 415:
throw new UnsupportedMediaTypeHttpException;
}
}
}