Completed
Push — 57-formatter-per-extension ( 73b3c8 )
by Nicolas
40:17 queued 36:16
created

Rules::convertRules()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 18
rs 9.2
cc 4
eloc 9
nc 3
nop 1
1
<?php
2
3
namespace Karma\Formatters;
4
5
use Karma\Formatter;
6
7
class Rules implements Formatter
8
{
9
    private
10
        $rules;
11
    
12
    public function __construct(array $rules)
13
    {
14
        $this->convertRules($rules);
15
    }
16
    
17
    private function getSpecialValuesMappingTable()
18
    {
19
        return array(
20
            '<true>' => true,
21
            '<false>' => false,
22
            '<null>' => null,
23
            '<string>' => function($value) {
24
                return is_string($value);
25
            }
26
        );
27
    }
28
    
29
    private function convertRules(array $rules)
30
    {
31
        $this->rules = array();
32
        $mapping = $this->getSpecialValuesMappingTable();
33
        
34
        foreach($rules as $value => $result)
35
        {
36
            $value = trim($value);
37
            
38
            if(is_string($value) && array_key_exists($value, $mapping))
39
            {
40
                $result = $this->handleStringFormatting($value, $result);
41
                $value = $mapping[$value];
42
            }
43
            
44
            $this->rules[] = array($value, $result);
45
        }    
46
    }
47
    
48
    private function handleStringFormatting($value, $result)
49
    {
50
        if($value === '<string>')
51
        {
52
            $result = function ($value) use ($result) {
53
                return str_replace('<string>', $value, $result);
54
            };
55
        }
56
        
57
        return $result;
58
    }
59
    
60
    public function format($value)
61
    {
62
        foreach($this->rules as $rule)
63
        {
64
            list($condition, $result) = $rule;
65
            
66
            if($this->isRuleMatches($condition, $value))
67
            {
68
                return $this->applyFormattingRule($result, $value);
69
            }
70
        }
71
        
72
        return $value;
73
    }
74
    
75
    private function isRuleMatches($condition, $value)
76
    {
77
        $hasMatched = ($condition === $value);
78
        
79
        if($condition instanceof \Closure)
80
        {
81
            $hasMatched = $condition($value);
82
        }    
83
        
84
        return $hasMatched;
85
    }
86
    
87
    private function applyFormattingRule($ruleResult, $value)
88
    {
89
        if($ruleResult instanceof \Closure)
90
        {
91
            return $ruleResult($value);
92
        }
93
        
94
        return $ruleResult;
95
    }
96
}
97