Completed
Push — develop ( bc21b0...0bdfd4 )
by Adam
24:26 queued 09:29
created

src/Common/Hydrator/ModelHydrator.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace IBM\Watson\Common\Hydrator;
4
5
use IBM\Watson\Common\Exception\HydrationException;
6
use IBM\Watson\Common\Model\ApiResponseInterface;
7
use Psr\Http\Message\ResponseInterface;
8
9
final class ModelHydrator implements HydratorInterface
10
{
11
    /**
12
     * Hydrate API response
13
     *
14
     * @param \Psr\Http\Message\ResponseInterface $response
15
     * @param string|null                         $class
16
     *
17
     * @return mixed
18
     *
19
     * @throws \IBM\Watson\Common\Exception\HydrationException
20
     */
21
    public function hydrate(ResponseInterface $response, $class = null)
22
    {
23
        if (null === $class) {
24
            throw new HydrationException('The ModelHydrator requires a model class as the second parameter');
25
        }
26
27
        $body = $response->getBody()->__toString();
28 View Code Duplication
        if (\strpos($response->getHeaderLine('Content-Type'), 'application/json') !== 0) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
29
            $message = 'The ModelHydrator cannot hydrate response with Content-Type: ';
30
            throw new HydrationException($message . $response->getHeaderLine('Content-Type'));
31
        }
32
33
        $data = \json_decode($body, true);
34
        if (\JSON_ERROR_NONE !== \json_last_error()) {
35
            throw new HydrationException(\sprintf(
36
                'Error (%d) when trying to json_decode response',
37
                \json_last_error()
38
            ));
39
        }
40
41
        if (\is_subclass_of($class, ApiResponseInterface::class)) {
42
            $model = \call_user_func($class.'::create', $data);
43
        } else {
44
            $model = new $class($data);
45
        }
46
47
        return $model;
48
    }
49
}
50