AbstractObject::fromArray()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 13
rs 10
1
<?php
2
3
namespace Viktoras\Scryfall\Entities;
4
5
use Viktoras\Scryfall\Exception\InvalidArgumentException;
6
7
abstract class AbstractObject implements ObjectInterface
8
{
9
    abstract protected function acceptsObject(): string;
10
11
    /**
12
     * Prevent from overriding constructor.
13
     */
14
    final public function __construct()
15
    {
16
    }
17
18
    /**
19
     * @return ObjectInterface|static
20
     *
21
     * @throws InvalidArgumentException
22
     */
23
    public static function fromJsonString(string $json): ObjectInterface
24
    {
25
        $instance = new static();
26
27
        return static::fromArray($instance->validateInput($json));
28
    }
29
30
    public static function fromArray(array $data): ObjectInterface
31
    {
32
        $instance = new static();
33
34
        foreach ($data as $key => $value) {
35
            $methodName = 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $key)));
36
37
            if (method_exists($instance, $methodName)) {
38
                $instance->$methodName($value);
39
            }
40
        }
41
42
        return $instance;
43
    }
44
45
    /**
46
     * @return array JSON decoded into array
47
     */
48
    public function validateInput(string $json): array
49
    {
50
        $data = json_decode($json, true);
51
52
        if (!is_array($data) || !isset($data['object']) || $data['object'] !== $this->acceptsObject()) {
53
            throw new InvalidArgumentException('Invalid object');
54
        }
55
56
        return $data;
57
    }
58
}
59