ObjectFactory::makeFromArray()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 6
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 14
rs 10
1
<?php
2
3
namespace Viktoras\Scryfall\Entities;
4
5
use Viktoras\Scryfall\Exception\InvalidArgumentException;
6
use Viktoras\Scryfall\Exception\UnexpectedValueException;
7
8
class ObjectFactory
9
{
10
    /**
11
     * Some objects conflict with PHP reserved names, use this custom mapping
12
     * for alternative names.
13
     */
14
    private const CLASS_MAPPING = [
15
        'list' => ListObject::class
16
    ];
17
18
    public function makeFromString(string $json): ObjectInterface
19
    {
20
        $data = json_decode($json, true);
21
22
        if (!is_array($data)) {
23
            $data = [];
24
        }
25
26
        return $this->makeFromArray($data);
27
    }
28
29
    public function makeFromArray(array $data): ObjectInterface
30
    {
31
        if (!isset($data['object'])) {
32
            throw new InvalidArgumentException('Invalid data format');
33
        }
34
35
        // Load class name from map or generate one
36
        $type = self::CLASS_MAPPING[$data['object']] ?? __NAMESPACE__ . '\\' . ucfirst($data['object']);
37
38
        if (!class_exists($type) || !in_array(ObjectInterface::class, class_implements($type), true)) {
39
            throw new UnexpectedValueException('Unsupported object');
40
        }
41
42
        return $type::fromArray($data);
43
    }
44
}
45