ValidationRuleParser::explodeRules()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 22
rs 9.8666
cc 4
nc 6
nop 0
1
<?php
2
3
namespace Cube\SilverStripe\Validation;
4
5
/**
6
 * Class ValidationRuleParser
7
 * @package Cube\SilverStripe\Validation
8
 */
9
class ValidationRuleParser
10
{
11
    /**
12
     * The rules that need to be parsed
13
     *
14
     * @var array
15
     */
16
    private $rules;
17
18
    /**
19
     * The parsed rules
20
     * @var
21
     */
22
    private $data = [];
23
24
    /**
25
     * The current rule parsing
26
     *
27
     * @var
28
     */
29
    private $currentRule;
30
31
    /**
32
     * On instantiation add the desired rules
33
     * into a global accessible variable.
34
     *
35
     * @param  array  $rules
36
     * @return void
37
     */
38
    public function __construct(array $rules)
39
    {
40
        $this->rules = $rules;
41
    }
42
43
    /**
44
     * Parse an array of rules to the format
45
     * used in @see \Valitron\Validator validation.
46
     */
47
    private function parse()
48
    {
49
        foreach ($this->rules as $field => $rule) {
50
            $this->currentRule = $rule;
51
            $this->data[$field] = $this->explodeRules();
52
        }
53
    }
54
55
    /**
56
     * Explode the current rule
57
     */
58
    private function explodeRules()
59
    {
60
        $exploded = [];
61
        $rules = $this->currentRule;
62
63
        if (!is_array($this->currentRule)) {
64
            $rules = explode('|', $this->currentRule);
65
        }
66
67
        foreach ($rules as $rule) {
68
            $arguments = [];
69
70
            if (strpos($rule, ':') !== false) {
71
                $argumentStr = substr($rule, strpos($rule, ':') + 1);
72
                $arguments = explode(',', $argumentStr);
73
                $rule = substr($rule, 0, strpos($rule, ':'));
74
            }
75
76
            $exploded[$rule] = $arguments;
77
        }
78
79
        return $exploded;
80
    }
81
82
    /**
83
     * Retrieve the parsed data
84
     *
85
     * @return array
86
     */
87
    public function getData() : array
88
    {
89
        return $this->data;
90
    }
91
92
    /**
93
     * Static Factory for the this class.
94
     * This will create a new instance of this class and
95
     * parse the given rules to the correct format.
96
     *
97
     * @param array $rules The rules that needs to be parsed
98
     * @return ValidationRuleParser
99
     */
100
    public static function make(array $rules) : ValidationRuleParser
101
    {
102
        $parser = new static($rules);
103
104
        $parser->parse();
105
106
        return $parser;
107
    }
108
}
109