ModelHydrator   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 27
Duplicated Lines 11.11 %

Coupling/Cohesion

Components 0
Dependencies 3

Test Coverage

Coverage 72.72%

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 3
dl 3
loc 27
ccs 8
cts 11
cp 0.7272
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A hydrate() 3 18 4

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
declare(strict_types=1);
4
5
/*
6
 * This software may be modified and distributed under the terms
7
 * of the MIT license. See the LICENSE file for details.
8
 */
9
10
namespace Billogram\Hydrator;
11
12
use Billogram\Exception\HydrationException;
13
use Billogram\Model\CreatableFromArray;
14
use Psr\Http\Message\ResponseInterface;
15
16
/**
17
 * Hydrate an HTTP response to domain object.
18
 *
19
 * @author Tobias Nyholm <[email protected]>
20
 */
21
final class ModelHydrator implements Hydrator
22
{
23
    /**
24
     * @param ResponseInterface $response
25
     * @param string            $class
26
     *
27
     * @return mixed
28
     */
29 19
    public function hydrate(ResponseInterface $response, string $class)
30
    {
31 19
        $body = $response->getBody()->__toString();
32 19 View Code Duplication
        if (0 !== strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
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...
33
            throw new HydrationException('The ModelHydrator cannot hydrate response with Content-Type:'.$response->getHeaderLine('Content-Type'));
34
        }
35 19
        $data = json_decode($body, true);
36 19
        if (JSON_ERROR_NONE !== json_last_error()) {
37
            throw new HydrationException(sprintf('Error (%d) when trying to json_decode response', json_last_error()));
38
        }
39 19
        if (is_subclass_of($class, CreatableFromArray::class)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Billogram\Model\CreatableFromArray::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
40 19
            $object = call_user_func($class.'::createFromArray', $data);
41
        } else {
42
            $object = new $class($data);
43
        }
44
45 19
        return $object;
46
    }
47
}
48