AbstractResponseInspector   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5
Metric Value
wmc 7
lcom 0
cbo 5
dl 0
loc 55
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A decodeResponseBody() 0 4 1
A filterCommonErrors() 0 11 3
A newBadRequestException() 0 10 1
A decodeData() 0 6 2
1
<?php
2
3
namespace RayRutjes\GetEventStore\Client\Http;
4
5
use Psr\Http\Message\ResponseInterface;
6
use RayRutjes\GetEventStore\Client\Exception\AccessDeniedException;
7
use RayRutjes\GetEventStore\Client\Exception\BadRequestException;
8
use RayRutjes\GetEventStore\Client\Exception\StreamDeletedException;
9
10
abstract class AbstractResponseInspector implements ResponseInspector
11
{
12
    /**
13
     * @param ResponseInterface $response
14
     */
15
    protected function filterCommonErrors(ResponseInterface $response)
16
    {
17
        // Globally catch 401 responses, as for now we don't care of the operation context.
18
        if ($response->getStatusCode() === 401) {
19
            throw new AccessDeniedException($response->getReasonPhrase(), $response->getStatusCode());
20
        }
21
22
        if ($response->getStatusCode() === 410) {
23
            throw new StreamDeletedException($response->getReasonPhrase(), $response->getStatusCode());
24
        }
25
    }
26
27
    /**
28
     * @param $response
29
     *
30
     * @return BadRequestException
31
     */
32
    protected function newBadRequestException(ResponseInterface $response)
33
    {
34
        $message = sprintf(
35
            'Unhandled response code %d: %s',
36
            $response->getStatusCode(),
37
            $response->getReasonPhrase()
38
        );
39
40
        return new BadRequestException($message, $response->getStatusCode());
41
    }
42
43
    /**
44
     * @param ResponseInterface $response
45
     *
46
     * @return array
47
     */
48
    protected function decodeResponseBody(ResponseInterface $response): array
49
    {
50
        return $this->decodeData($response->getBody()->getContents());
51
    }
52
53
    /**
54
     * @param string $data
55
     *
56
     * @return array
57
     */
58
    protected function decodeData(string $data): array
59
    {
60
        $decoded = json_decode($data, true);
61
62
        return !is_array($decoded) ? [] : $decoded;
63
    }
64
}
65