AbstractHydrator   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 11
dl 0
loc 44
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isJsonResponse() 0 3 1
A getBody() 0 3 1
A getBodyContent() 0 13 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace IBM\Watson\Common\Hydrator;
6
7
use IBM\Watson\Common\Exception\JsonException;
8
use Psr\Http\Message\ResponseInterface;
9
10
/**
11
 * AbstractHydrator provides common protected methods other hydrators might need to use.
12
 */
13
abstract class AbstractHydrator implements HydratorInterface
14
{
15
    const HEADER_CONTENT_TYPE = 'Content-Type';
16
17
    /**
18
     * @param \Psr\Http\Message\ResponseInterface $response Response to check.
19
     *
20
     * @return bool
21
     */
22
    protected function isJsonResponse(ResponseInterface $response): bool
23
    {
24
        return 0 === \strpos($response->getHeaderLine(self::HEADER_CONTENT_TYPE), 'application/json');
25
    }
26
27
    /**
28
     * @param \Psr\Http\Message\ResponseInterface $response Response to parse.
29
     *
30
     * @return string
31
     */
32
    protected function getBody(ResponseInterface $response): string
33
    {
34
        return $response->getBody()->__toString();
35
    }
36
37
    /**
38
     * @param \Psr\Http\Message\ResponseInterface $response Response to parse.
39
     *
40
     * @return array
41
     *
42
     * @throws \IBM\Watson\Common\Exception\JsonException
43
     */
44
    protected function getBodyContent(ResponseInterface $response): array
45
    {
46
        $json = json_decode($this->getBody($response), true);
47
48
        if (JSON_ERROR_NONE !== json_last_error()) {
49
            throw new JsonException(sprintf(
50
                'Error (%d) when trying to json_decode response: %s',
51
                \json_last_error(),
52
                \json_last_error_msg()
53
            ));
54
        }
55
56
        return $json;
57
    }
58
}
59