Passed
Pull Request — develop (#22)
by Adam
01:58
created

ArrayHydrator   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 28
rs 10
c 0
b 0
f 0
wmc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A hydrate() 0 18 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace IBM\Watson\Common\Hydrator;
6
7
use IBM\Watson\Common\Exception\HydrationException;
8
use Psr\Http\Message\ResponseInterface;
9
10
/**
11
 * The ArrayHydrator will hydrate a json response into an associative array.
12
 */
13
class ArrayHydrator extends AbstractHydrator
14
{
15
    /**
16
     * @param \Psr\Http\Message\ResponseInterface $response Response to hydrate.
17
     * @param string|null                         $class    Class to hydrate to.
18
     *
19
     * @return array
20
     *
21
     * @throws \IBM\Watson\Common\Exception\HydrationException
22
     */
23
    public function hydrate(ResponseInterface $response, string $class = null): array
24
    {
25
        if (!$this->isJsonResponse($response)) {
26
            $message = 'The ArrayHydrator cannot hydrate a response with Content-Type: ';
27
28
            throw new HydrationException($message.$response->getHeaderLine(self::HEADER_CONTENT_TYPE));
29
        }
30
31
        $body = $this->getBodyContent($response);
32
        if (JSON_ERROR_NONE !== \json_last_error()) {
33
            throw new HydrationException(sprintf(
34
                'Error (%d) when trying to json_decode response: %s',
35
                \json_last_error(),
36
                \json_last_error_msg()
37
            ));
38
        }
39
40
        return $body;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $body could return the type null which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
41
    }
42
}
43