Failed Conditions
Push — master ( da580a...04820f )
by Moesjarraf
03:10
created

Transform::applyToNode()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 27
ccs 17
cts 17
cp 1
rs 8.439
cc 6
eloc 14
nc 9
nop 1
crap 6
1
<?php
2
3
namespace LegalThings\DataEnricher\Processor;
4
5
use LegalThings\DataEnricher\Node;
6
use LegalThings\DataEnricher\Processor;
7
8
/**
9
 * Transform processor, apply transformation functions on data
10
 */
11
class Transform implements Processor
12
{
13
    use Processor\Implementation;
14
    
15
    /**
16
     * Default transformation functions
17
     * @var array
18
     */
19
    public static $defaultFunctions = [
20
        'hash' => 'hash',
21
        'base64_encode' => 'base64_encode',
22
        'base64_decode' => 'base64_decode',
23
        'json_encode' => 'json_encode',
24
        'json_decode' => 'json_decode',
25
        'serialize' => 'serialize',
26
        'unserialize' => 'unserialize',
27
        'strtotime' => 'strtotime',
28
        'date' => 'date'
29
    ];
30
    
31
    /**
32
     * Allowed transformation functions
33
     * @var array 
34
     */
35
    public $functions;
36
    
37
    
38
    /**
39
     * Class constructor
40
     * 
41
     * @param string $property  Property key with the processing instruction
42
     */
43 9
    public function __construct($property)
44
    {
45 9
        $this->property = $property;
46 9
        $this->functions = static::$defaultFunctions;
47 9
    }
48
    
49
    /**
50
     * Apply processing to a single node
51
     * 
52
     * @param Node $node
53
     */
54 6
    public function applyToNode(Node $node)
55
    {
56 6
        $transformations = (array)$node->getInstruction($this);
57
        
58 6
        if (!isset($node->input)) {
59 1
            return;
60
        }
61
        
62 5
        $value = $node->input;
63
        
64 5
        if ($value instanceof Node) {
65 1
            $value = $value->getResult();
66 1
        }
67
        
68 5
        foreach ($transformations as $transformation) {
69 5
            list($key, $arg) = explode(':', $transformation) + [null, null];
70
            
71 5
            if (!isset($this->functions[$key])) {
72 1
                throw new \Exception("Unknown transformation '$transformation'");
73
            }
74
            
75 4
            $fn = $this->functions[$key];
76 4
            $value = isset($arg) ? call_user_func($fn, $arg, $value) : call_user_func($fn, $value);
77 4
        }
78
        
79 4
        $node->setResult($value);
80 4
    }
81
}
82