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
|
|
|
|