|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace LegalThings\DataEnricher\Processor; |
|
4
|
|
|
|
|
5
|
|
|
use LegalThings\DataEnricher\Node; |
|
6
|
|
|
use LegalThings\DataEnricher\Processor; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Merge multiple object into one |
|
10
|
|
|
*/ |
|
11
|
|
|
class Merge implements Processor |
|
12
|
|
|
{ |
|
13
|
|
|
use Processor\Implementation; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Apply processing to a single node |
|
17
|
|
|
* |
|
18
|
|
|
* @param Node $node |
|
19
|
|
|
*/ |
|
20
|
3 |
|
public function applyToNode(Node $node) |
|
21
|
|
|
{ |
|
22
|
3 |
|
$instruction = $node->getInstruction($this); |
|
23
|
|
|
|
|
24
|
3 |
|
$list = $this->resolve($instruction); |
|
25
|
|
|
|
|
26
|
3 |
|
$result = $this->merge($list); |
|
27
|
3 |
|
$node->setResult($result); |
|
28
|
3 |
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* Resolve processing nodes in the instruction |
|
32
|
|
|
* |
|
33
|
|
|
* @param array $list |
|
34
|
|
|
* @return array |
|
35
|
|
|
*/ |
|
36
|
3 |
|
public function resolve($list) |
|
37
|
|
|
{ |
|
38
|
3 |
|
if ($list instanceof Node) { |
|
39
|
|
|
$list = $list->getResult(); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
3 |
|
foreach ($list as &$item) { |
|
43
|
3 |
|
if ($item instanceof Node) { |
|
44
|
1 |
|
$item = $item->getResult(); |
|
45
|
1 |
|
} |
|
46
|
|
|
|
|
47
|
3 |
|
if ($item instanceof \Traversable) { |
|
48
|
|
|
$item = iterator_to_array($item); |
|
49
|
|
|
} |
|
50
|
3 |
|
} |
|
51
|
|
|
|
|
52
|
3 |
|
return $list; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* Merge properties of an object |
|
57
|
|
|
* |
|
58
|
|
|
* @param array $list |
|
59
|
|
|
* @return \stdClass|array|string |
|
60
|
|
|
*/ |
|
61
|
3 |
|
protected function merge(array $list) |
|
|
|
|
|
|
62
|
|
|
{ |
|
63
|
3 |
|
if (empty($list)) { |
|
64
|
|
|
return null; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
3 |
|
$scalar = false; |
|
68
|
|
|
|
|
69
|
3 |
|
foreach ($list as &$item) { |
|
70
|
3 |
|
if (is_object($item)) { |
|
71
|
2 |
|
$item = get_object_vars($item); |
|
72
|
2 |
|
} |
|
73
|
|
|
|
|
74
|
3 |
|
$scalar = is_scalar($item); |
|
75
|
3 |
|
} |
|
76
|
|
|
|
|
77
|
3 |
|
if ($scalar) { |
|
78
|
|
|
$result = join('', $list); |
|
79
|
|
|
} else { |
|
80
|
3 |
|
$result = call_user_func_array('array_merge', $list); |
|
81
|
|
|
|
|
82
|
|
|
// Is associative array |
|
83
|
3 |
|
if (array_keys($result) !== array_keys(array_keys($result))) { |
|
84
|
2 |
|
$result = (object)$result; |
|
85
|
2 |
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|
|
88
|
3 |
|
return $result; |
|
89
|
|
|
} |
|
90
|
|
|
} |
|
91
|
|
|
|