1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace LegalThings\DataEnricher\Processor; |
4
|
|
|
|
5
|
|
|
use LegalThings\DataEnricher\Node; |
6
|
|
|
use LegalThings\DataEnricher\Processor; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Enriches objects in arrays by matching them |
10
|
|
|
*/ |
11
|
|
|
class Enrich 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 |
|
if (is_array($instruction) || is_object($instruction)) { |
25
|
3 |
|
$instruction = (object)$instruction; |
26
|
3 |
|
} |
27
|
|
|
|
28
|
3 |
|
$source = isset($instruction->input) ? $instruction->input : ($node->getResult() ?: []); |
29
|
|
|
|
30
|
3 |
|
if (is_string($instruction->match)) { |
31
|
2 |
|
$match = ['extra' => $instruction->match, 'source' => $instruction->match]; |
32
|
2 |
|
} else { |
33
|
1 |
|
$match = (array)$instruction->match; |
34
|
|
|
} |
35
|
|
|
|
36
|
3 |
|
$extraIndexed = []; |
37
|
|
|
|
38
|
3 |
View Code Duplication |
foreach ($instruction->extra as $extra) { |
|
|
|
|
39
|
3 |
|
$key = \Jasny\DotKey::on($extra)->get($match['extra']); |
40
|
|
|
|
41
|
3 |
|
if (!isset($key) || isset($extraIndexed[$key])) { |
42
|
|
|
continue; |
43
|
|
|
} |
44
|
|
|
|
45
|
3 |
|
if (!is_scalar($key)) { |
46
|
|
|
trigger_error("Trying to match on non-scalar type", E_USER_WARNING); |
47
|
|
|
continue; |
48
|
|
|
} |
49
|
|
|
|
50
|
3 |
|
$extraIndexed[$key] = $extra; |
51
|
3 |
|
} |
52
|
|
|
|
53
|
3 |
View Code Duplication |
foreach ($source as &$item) { |
|
|
|
|
54
|
3 |
|
$key = \Jasny\DotKey::on($item)->get($match['source']); |
55
|
|
|
|
56
|
3 |
|
if (!isset($key) || !isset($extraIndexed[$key])) { |
57
|
|
|
continue; |
58
|
|
|
} |
59
|
|
|
|
60
|
3 |
|
if (!is_scalar($key)) { |
61
|
|
|
trigger_error("Trying to match on non-scalar type", E_USER_WARNING); |
62
|
|
|
continue; |
63
|
|
|
} |
64
|
|
|
|
65
|
3 |
|
$item = array_merge((array)$item, (array)$extraIndexed[$key]); |
66
|
3 |
|
} |
67
|
|
|
|
68
|
3 |
|
$node->setResult($source); |
69
|
3 |
|
} |
70
|
|
|
} |
71
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.