|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the Ivory Google Map package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Eric GELOEN <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please read the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Ivory\GoogleMap\Service\Plugin; |
|
13
|
|
|
|
|
14
|
|
|
use Http\Client\Common\Exception\ClientErrorException; |
|
15
|
|
|
use Http\Client\Common\Exception\ServerErrorException; |
|
16
|
|
|
use Http\Client\Common\Plugin; |
|
17
|
|
|
use Psr\Http\Message\RequestInterface; |
|
18
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @author GeLo <[email protected]> |
|
22
|
|
|
*/ |
|
23
|
|
|
class ErrorPlugin implements Plugin |
|
24
|
|
|
{ |
|
25
|
|
|
/** |
|
26
|
|
|
* @var string[] |
|
27
|
|
|
*/ |
|
28
|
|
|
private static $errors = [ |
|
29
|
|
|
'ERROR' => ServerErrorException::class, |
|
30
|
|
|
'INVALID_REQUEST' => ClientErrorException::class, |
|
31
|
|
|
'MAX_DIMENSIONS_EXCEEDED' => ClientErrorException::class, |
|
32
|
|
|
'MAX_ELEMENTS_EXCEEDED' => ClientErrorException::class, |
|
33
|
|
|
'MAX_WAYPOINTS_EXCEEDED' => ClientErrorException::class, |
|
34
|
|
|
'NOT_FOUND' => ClientErrorException::class, |
|
35
|
|
|
'OVER_QUERY_LIMIT' => ServerErrorException::class, |
|
36
|
|
|
'REQUEST_DENIED' => ClientErrorException::class, |
|
37
|
|
|
'UNKNOWN_ERROR' => ServerErrorException::class, |
|
38
|
|
|
]; |
|
39
|
|
|
|
|
40
|
|
|
private static $placeholders = [ |
|
41
|
|
|
'"status" : "%s"', |
|
42
|
|
|
'<status>%s</status>', |
|
43
|
|
|
]; |
|
44
|
|
|
|
|
45
|
|
|
public function handleRequest(RequestInterface $request, callable $next, callable $first) |
|
46
|
|
|
{ |
|
47
|
|
|
return $next($request)->then(function (ResponseInterface $response) use ($request) { |
|
48
|
|
|
return $this->transformResponseToException($request, $response); |
|
49
|
|
|
}); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
protected function transformResponseToException(RequestInterface $request, ResponseInterface $response): ResponseInterface |
|
53
|
|
|
{ |
|
54
|
|
|
$bodyStream = $response->getBody(); |
|
55
|
|
|
$body = $bodyStream->__toString(); |
|
56
|
|
|
if ($bodyStream->isSeekable()) { |
|
57
|
|
|
$bodyStream->rewind(); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
foreach (self::$errors as $error => $exception) { |
|
61
|
|
|
foreach (self::$placeholders as $placeholder) { |
|
62
|
|
|
if (false !== strpos($body, sprintf($placeholder, $error))) { |
|
63
|
|
|
throw new $exception($error, $request, $response); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
return $response; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|