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

UnsafeNodeFactory   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Test Coverage

Coverage 62.5%

Importance

Changes 0
Metric Value
wmc 12
dl 0
loc 58
ccs 15
cts 24
cp 0.625
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A createNodeFromObject() 0 5 2
A createVectorNodeFromArray() 0 15 4
B createNodeFromValue() 0 23 6
1
<?php declare(strict_types=1);
2
3
namespace DaveRandom\Jom;
4
5
use DaveRandom\Jom\Exceptions\InvalidNodeValueException;
6
7
final class UnsafeNodeFactory extends NodeFactory
8
{
9
    /**
10
     * @throws InvalidNodeValueException
11
     */
12 10
    private function createVectorNodeFromArray(array $values, ?Document $doc): VectorNode
13
    {
14 10
        $i = 0;
15 10
        $packed = true;
16
17 10
        foreach ($values as $key => $value) {
18 6
            if ($key !== $i++) {
19
                $packed = false;
20 6
                break;
21
            }
22
        }
23
24 10
        return $packed
25 10
            ? $this->createArrayNodeFromPackedArray($values, $doc)
26 10
            : $this->createObjectNodeFromPropertyMap($values, $doc);
27
    }
28
29
    /**
30
     * @throws InvalidNodeValueException
31
     */
32
    private function createNodeFromObject(object $object, ?Document $doc): Node
33
    {
34
        return $object instanceof \JsonSerializable
35
            ? $this->createNodeFromValue($object->jsonSerialize(), $doc)
36
            : $this->createObjectNodeFromPropertyMap($object, $doc);
37
    }
38
39
    /**
40
     * @inheritdoc
41
     */
42 15
    public function createNodeFromValue($value, ?Document $doc = null): Node
43
    {
44
        try {
45 15
            if (null !== $node = $this->createScalarOrNullNodeFromValue($value, $doc)) {
46 13
                return $node;
47
            }
48
49 10
            if (\is_object($value)) {
50
                return $this->createNodeFromObject($value, $doc);
51
            }
52
53 10
            if (\is_array($value)) {
54 10
                return $this->createVectorNodeFromArray($value, $doc);
55
            }
56
        } catch (InvalidNodeValueException $e) {
57
            throw $e;
58
        //@codeCoverageIgnoreStart
59
        } catch (\Exception $e) {
60
            throw new \Error('Unexpected ' . \get_class($e) . ": {$e->getMessage()}", 0, $e);
61
        }
62
        //@codeCoverageIgnoreEnd
63
64
        throw new InvalidNodeValueException("Failed to create node from value of type '" . \gettype($value) . "'");
65
    }
66
}
67