1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Http\Client\Plugin; |
4
|
|
|
|
5
|
|
|
use Http\Client\Plugin\Exception\ClientErrorException; |
6
|
|
|
use Http\Client\Plugin\Exception\ServerErrorException; |
7
|
|
|
use Psr\Http\Message\RequestInterface; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Throw exception when the response of a request is not acceptable. |
12
|
|
|
* |
13
|
|
|
* By default an exception will be thrown for all status codes from 400 to 599. |
14
|
|
|
* |
15
|
|
|
* @author Joel Wurtz <[email protected]> |
16
|
|
|
*/ |
17
|
|
|
class ErrorPlugin implements Plugin |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* {@inheritdoc} |
21
|
|
|
*/ |
22
|
3 |
|
public function handleRequest(RequestInterface $request, callable $next, callable $first) |
23
|
|
|
{ |
24
|
3 |
|
$promise = $next($request); |
25
|
|
|
|
26
|
3 |
|
return $promise->then(function (ResponseInterface $response) use ($request) { |
27
|
3 |
|
return $this->transformResponseToException($request, $response); |
28
|
3 |
|
}); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Transform response to an error if possible. |
33
|
|
|
* |
34
|
|
|
* @param RequestInterface $request Request of the call |
35
|
|
|
* @param ResponseInterface $response Response of the call |
36
|
|
|
* |
37
|
|
|
* @throws ClientErrorException If response status code is a 4xx |
38
|
|
|
* @throws ServerErrorException If response status code is a 5xx |
39
|
|
|
* |
40
|
|
|
* @return ResponseInterface If status code is not in 4xx or 5xx return response |
41
|
|
|
*/ |
42
|
3 |
|
protected function transformResponseToException(RequestInterface $request, ResponseInterface $response) |
43
|
|
|
{ |
44
|
3 |
View Code Duplication |
if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) { |
|
|
|
|
45
|
1 |
|
throw new ClientErrorException($response->getReasonPhrase(), $request, $response); |
46
|
|
|
} |
47
|
|
|
|
48
|
2 |
View Code Duplication |
if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600) { |
|
|
|
|
49
|
1 |
|
throw new ServerErrorException($response->getReasonPhrase(), $request, $response); |
50
|
|
|
} |
51
|
|
|
|
52
|
1 |
|
return $response; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.