ObjectFactory   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 35
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A makeFromString() 0 9 2
A makeFromArray() 0 14 4
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