Hydration::doHydrate()   B
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 8
cts 8
cp 1
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 8
nc 6
nop 1
crap 5
1
<?php
2
3
/*
4
 * This file is part of the PhpMob package.
5
 *
6
 * (c) Ishmael Doss <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace PhpMob\Omise\Hydrator;
15
16
use PhpMob\Omise\Domain\Error;
17
use PhpMob\Omise\Exception\InvalidResponseException;
18
use PhpMob\Omise\Model;
19
20
/**
21
 * @author Ishmael Doss <[email protected]>
22
 */
23
class Hydration implements HydrationInterface
24
{
25
    /**
26
     * TODO: improve me
27
     *
28
     * @param array $data
29
     *
30
     * @return Model|array
31
     */
32 51
    private function doHydrate(array &$data)
33
    {
34 51
        foreach ($data as $key => $value) {
35 51
            if (is_array($value)) {
36 34
                $data[$key] = self::doHydrate($data[$key]);
37
            }
38
        }
39
40 51
        if (empty($data) || empty($data['object'])) {
41 22
            return $data;
42
        }
43
44 51
        $domain = static::getDomainClass($data['object']);
45
46 51
        return new $domain($data);
47
    }
48
49
    /**
50
     * @param string $rawData
51
     *
52
     * @return Model
53
     *
54
     * @throws InvalidResponseException
55
     */
56 51
    public function hydrate($rawData)
57
    {
58 51
        $data = json_decode($rawData, true);
59 51
        $domain = $this->doHydrate($data);
60 51
        $assertingClass = static::getDomainAssertionClass();
61
62 51
        if (!$domain instanceof $assertingClass) {
63
            throw new InvalidResponseException(new Error([
64
                'code' => 'unsupported_format',
65
                'message' => 'Unsupported format.',
66
                'data' => $domain,
67
            ]));
68
        }
69
70 51
        return $domain;
71
    }
72
73
    /**
74
     * @param $className
75
     *
76
     * @return string
77
     */
78
    public static function getDomainClass($className)
79
    {
80
        return 'PhpMob\\Omise\\Domain\\' . ucfirst($className === 'list' ? 'Pagination' : $className);
81
    }
82
83
    /**
84
     * @return string
85
     */
86
    public static function getDomainAssertionClass()
87
    {
88
        return Model::class;
89
    }
90
}
91