Completed
Push — master ( 5d9a5d...e6d18b )
by Chris
02:53
created

NodeFactory::createArrayNodeFromPackedArray()   A

Complexity

Conditions 4
Paths 7

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.3731

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 5
cts 7
cp 0.7143
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 7
nop 2
crap 4.3731
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
        //@codeCoverageIgnoreStart
32
        } catch (\Exception $e) {
33
            throw new \Error('Unexpected ' . \get_class($e) . ": {$e->getMessage()}", 0, $e);
34
        }
35
        //@codeCoverageIgnoreEnd
36
    }
37
38
    /**
39
     * @throws InvalidNodeValueException
40
     */
41
    final protected function createObjectNodeFromPropertyMap($properties, ?Document $doc): ObjectNode
42
    {
43
        try {
44
            $node = new ObjectNode([], $doc);
45
46
            foreach ($properties as $name => $value) {
47
                $node->setProperty($name, $this->createNodeFromValue($value, $doc));
48
            }
49
50
            return $node;
51
        } catch (InvalidNodeValueException $e) {
52
            throw $e;
53
        //@codeCoverageIgnoreStart
54
        } catch (\Exception $e) {
55
            throw new \Error('Unexpected ' . \get_class($e) . ": {$e->getMessage()}", 0, $e);
56
        }
57
        //@codeCoverageIgnoreEnd
58
    }
59
60 15
    final protected function createScalarOrNullNodeFromValue($value, ?Document $doc): ?Node
61
    {
62 15
        if ($value === null) {
63 13
            return new NullNode($doc);
64
        }
65
66 10
        $className = self::SCALAR_VALUE_NODE_CLASSES[\gettype($value)] ?? null;
67
68 10
        if ($className !== null) {
69
            return new $className($value, $doc);
70
        }
71
72 10
        return null;
73
    }
74
75
    /**
76
     * @throws InvalidNodeValueException
77
     */
78
    abstract public function createNodeFromValue($value, ?Document $doc = null): Node;
79
}
80