Completed
Push — master ( 39762b...5dff0a )
by Samuel
12s queued 11s
created

ErrorPlugin   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 2
dl 0
loc 48
ccs 0
cts 22
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A handleRequest() 0 6 1
A transformResponseToException() 0 18 5
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