Completed
Push — master ( f400d6...2675c1 )
by Chris
02:17
created

NodeFactory::createObjectNodeFromPropertyMap()   A

Complexity

Conditions 4
Paths 7

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 14
c 0
b 0
f 0
ccs 0
cts 9
cp 0
rs 9.2
cc 4
eloc 9
nc 7
nop 2
crap 20
1
<?php declare(strict_types=1);
2
3
namespace DaveRandom\Jom;
4
5
use DaveRandom\Jom\Exceptions\InvalidNodeValueException;
6
7
abstract class NodeFactory
8
{
9
    private const SCALAR_VALUE_NODE_CLASSES = [
10
        'boolean' => BooleanNode::class,
11
        'integer' => NumberNode::class,
12
        'double' => NumberNode::class,
13
        'string' => StringNode::class,
14
    ];
15
16
    /**
17
     * @throws InvalidNodeValueException
18
     */
19 10
    final protected function createArrayNodeFromPackedArray(array $values, ?Document $doc): ArrayNode
20
    {
21
        try {
22 10
            $node = new ArrayNode([], $doc);
23
24 10
            foreach ($values as $value) {
25 6
                $node->push($this->createNodeFromValue($value, $doc));
26
            }
27
28 10
            return $node;
29
        } catch (InvalidNodeValueException $e) {
30
            throw $e;
31
        } catch (\Exception $e) {
32
            throw new \Error('Unexpected ' . \get_class($e) . ": {$e->getMessage()}", 0, $e);
33
        }
34
    }
35
36
    /**
37
     * @throws InvalidNodeValueException
38
     */
39
    final protected function createObjectNodeFromPropertyMap($properties, ?Document $doc): ObjectNode
40
    {
41
        try {
42
            $node = new ObjectNode([], $doc);
43
44
            foreach ($properties as $name => $value) {
45
                $node->setProperty($name, $this->createNodeFromValue($value, $doc));
46
            }
47
48
            return $node;
49
        } catch (InvalidNodeValueException $e) {
50
            throw $e;
51
        } catch (\Exception $e) {
52
            throw new \Error('Unexpected ' . \get_class($e) . ": {$e->getMessage()}", 0, $e);
53
        }
54
    }
55
56 15
    final protected function createScalarOrNullNodeFromValue($value, ?Document $doc): ?Node
57
    {
58 15
        if ($value === null) {
59 13
            return new NullNode($doc);
60
        }
61
62 10
        $className = self::SCALAR_VALUE_NODE_CLASSES[\gettype($value)] ?? null;
63
64 10
        if ($className !== null) {
65
            return new $className($value, $doc);
66
        }
67
68 10
        return null;
69
    }
70
71
    /**
72
     * @throws InvalidNodeValueException
73
     */
74
    abstract public function createNodeFromValue($value, ?Document $doc = null): Node;
75
}
76