elmage /
textng-php
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Elmage\TextNg\Exception; |
||
| 4 | |||
| 5 | use GuzzleHttp\Exception\RequestException; |
||
| 6 | use Psr\Http\Message\RequestInterface; |
||
| 7 | use Psr\Http\Message\ResponseInterface; |
||
| 8 | |||
| 9 | class HttpException extends RuntimeException |
||
| 10 | { |
||
| 11 | private $request; |
||
| 12 | private $response; |
||
| 13 | |||
| 14 | /** |
||
| 15 | * Wraps an API exception in the appropriate domain exception. |
||
| 16 | * |
||
| 17 | * @param RequestException $e The API exception |
||
| 18 | * |
||
| 19 | * @return HttpException |
||
| 20 | */ |
||
| 21 | 7 | public static function wrap(RequestException $e) |
|
| 22 | { |
||
| 23 | 7 | $response = $e->getResponse(); |
|
| 24 | |||
| 25 | 7 | $class = self::exceptionClass($response); |
|
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 26 | 7 | $message = $e->getMessage(); |
|
| 27 | |||
| 28 | 7 | return new $class($message, $e->getRequest(), $response, $e); |
|
| 29 | } |
||
| 30 | |||
| 31 | 7 | public function __construct($message, RequestInterface $request, ResponseInterface $response, \Exception $previous) |
|
| 32 | { |
||
| 33 | 7 | parent::__construct($message, 0, $previous); |
|
| 34 | |||
| 35 | 7 | $this->request = $request; |
|
| 36 | 7 | $this->response = $response; |
|
| 37 | 7 | } |
|
| 38 | |||
| 39 | 7 | public function getRequest() |
|
| 40 | { |
||
| 41 | 7 | return $this->request; |
|
| 42 | } |
||
| 43 | |||
| 44 | 7 | public function getResponse() |
|
| 45 | { |
||
| 46 | 7 | return $this->response; |
|
| 47 | } |
||
| 48 | |||
| 49 | 7 | public function getStatusCode() |
|
| 50 | { |
||
| 51 | 7 | return $this->response->getStatusCode(); |
|
| 52 | } |
||
| 53 | |||
| 54 | 7 | private static function exceptionClass(ResponseInterface $response) |
|
| 55 | { |
||
| 56 | 7 | switch ($response->getStatusCode()) { |
|
| 57 | 7 | case 400: |
|
| 58 | 1 | return BadRequestException::class; |
|
| 59 | 6 | case 401: |
|
| 60 | 1 | return UnauthorizedException::class; |
|
| 61 | 5 | case 404: |
|
| 62 | 1 | return NotFoundException::class; |
|
| 63 | 4 | case 422: |
|
| 64 | 1 | return ValidationException::class; |
|
| 65 | 3 | case 500: |
|
| 66 | 1 | return InternalServerException::class; |
|
| 67 | 2 | case 503: |
|
| 68 | 1 | return ServiceUnavailableException::class; |
|
| 69 | default: |
||
| 70 | 1 | return HttpException::class; |
|
| 71 | } |
||
| 72 | } |
||
| 73 | } |
||
| 74 |