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

UnsafeNodeFactory::createNodeFromValue()   B

Complexity

Conditions 6
Paths 14

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 10.5

Importance

Changes 0
Metric Value
dl 0
loc 21
c 0
b 0
f 0
ccs 6
cts 12
cp 0.5
rs 8.7624
cc 6
eloc 12
nc 14
nop 2
crap 10.5
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
        } catch (\Exception $e) {
59
            throw new \Error('Unexpected ' . \get_class($e) . ": {$e->getMessage()}", 0, $e);
60
        }
61
62
        throw new InvalidNodeValueException("Failed to create node from value of type '" . \gettype($value) . "'");
63
    }
64
}
65