Completed
Pull Request — develop (#5)
by Adam
01:26
created

ModelHydrator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
Duplicated Lines 9.76 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 3
dl 4
loc 41
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B hydrate() 4 28 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace IBM\Watson\Common\Hydrator;
4
5
use IBM\Watson\Common\Exception\HydrationException;
6
use IBM\Watson\Common\Model\ApiResponse;
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
Duplication introduced by
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, ApiResponse::class)) {
42
            $model = \call_user_func($class.'::create', $data);
43
        } else {
44
            $model = new $class($data);
45
        }
46
47
        return $model;
48
    }
49
}
50