Completed
Push — master ( 04518a...0908bf )
by
01:37
created

Hydration::getDomainClass()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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