ErrorPlugin::transformResponseToException()   A
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 0
cts 15
cp 0
rs 9.3554
c 0
b 0
f 0
cc 5
nc 8
nop 2
crap 30
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 Http\Promise\Promise;
18
use Psr\Http\Message\RequestInterface;
19
use Psr\Http\Message\ResponseInterface;
20
21
/**
22
 * @author GeLo <[email protected]>
23
 */
24
class ErrorPlugin implements Plugin
25
{
26
    /**
27
     * @var string[]
28
     */
29
    private static $errors = [
30
        'ERROR'                   => ServerErrorException::class,
31
        'INVALID_REQUEST'         => ClientErrorException::class,
32
        'MAX_DIMENSIONS_EXCEEDED' => ClientErrorException::class,
33
        'MAX_ELEMENTS_EXCEEDED'   => ClientErrorException::class,
34
        'MAX_WAYPOINTS_EXCEEDED'  => ClientErrorException::class,
35
        'NOT_FOUND'               => ClientErrorException::class,
36
        'OVER_QUERY_LIMIT'        => ServerErrorException::class,
37
        'REQUEST_DENIED'          => ClientErrorException::class,
38
        'UNKNOWN_ERROR'           => ServerErrorException::class,
39
    ];
40
41
    private static $placeholders = [
42
        '"status" : "%s"',
43
        '<status>%s</status>',
44
    ];
45
46
    public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise
47
    {
48
        return $next($request)->then(function (ResponseInterface $response) use ($request) {
49
            return $this->transformResponseToException($request, $response);
50
        });
51
    }
52
53
    protected function transformResponseToException(RequestInterface $request, ResponseInterface $response): ResponseInterface
54
    {
55
        $bodyStream = $response->getBody();
56
        $body = $bodyStream->__toString();
57
        if ($bodyStream->isSeekable()) {
58
            $bodyStream->rewind();
59
        }
60
61
        foreach (self::$errors as $error => $exception) {
62
            foreach (self::$placeholders as $placeholder) {
63
                if (false !== strpos($body, sprintf($placeholder, $error))) {
64
                    throw new $exception($error, $request, $response);
65
                }
66
            }
67
        }
68
69
        return $response;
70
    }
71
}
72