Passed
Pull Request — develop (#22)
by Adam
01:46 queued 30s
created

ArrayHydrator::hydrate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 3
nop 2
dl 0
loc 18
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace IBM\Watson\Common\Hydrator;
6
7
use Psr\Http\Message\ResponseInterface;
8
9
/**
10
 * The ArrayHydrator will hydrate a json response into an associative array.
11
 */
12
class ArrayHydrator extends AbstractHydrator
13
{
14
    /**
15
     * @param \Psr\Http\Message\ResponseInterface $response Response to hydrate.
16
     * @param string|null                         $class    Class to hydrate to.
17
     *
18
     * @return array
19
     *
20
     * @throws \BadMethodCallException
21
     */
22
    public function hydrate(ResponseInterface $response, string $class = null): array
23
    {
24
        if (!$this->isJsonResponse($response)) {
25
            $message = 'The ArrayHydrator cannot hydrate a response with Content-Type: ';
26
27
            throw new \BadMethodCallException($message.$response->getHeaderLine(self::HEADER_CONTENT_TYPE));
28
        }
29
30
        $body = $this->getBodyContent($response);
31
        if (JSON_ERROR_NONE !== \json_last_error()) {
32
            throw new \BadMethodCallException(sprintf(
33
                'Error (%d) when trying to json_decode response: %s',
34
                \json_last_error(),
35
                \json_last_error_msg()
36
            ));
37
        }
38
39
        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...
40
    }
41
}
42