RuleHelper::validateArray()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 4
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace iamsaint\yml\helpers;
4
5
use iamsaint\yml\exceptions\IncorrectRuleException;
6
use iamsaint\yml\interfaces\Validator;
7
use function is_array;
8
use function is_string;
9
use function count;
10
use function class_exists;
11
12
/**
13
 * Class RuleHelper
14
 * @package iamsaint\yml\helpers
15
 */
16
class RuleHelper
17
{
18
    private const MIN_RULE_ARRAY_SIZE = 2;
19
20
    /**
21
     * @param $rule
22
     * @throws IncorrectRuleException
23
     */
24
    private static function validateArray($rule): void
25
    {
26
        if (!is_array($rule)) {
27
            throw new IncorrectRuleException('Rule must be array');
28
        }
29
    }
30
31
    /**
32
     * @param $rule
33
     * @throws IncorrectRuleException
34
     */
35
    private static function validateString($rule): void
36
    {
37
        if (!is_string($rule[1])) {
38
            throw new IncorrectRuleException('Rule name must be a string');
39
        }
40
    }
41
42
    /**
43
     * @param $rule
44
     * @throws IncorrectRuleException
45
     */
46
    private static function validateDefined($rule):void
47
    {
48
        if (count($rule) < self::MIN_RULE_ARRAY_SIZE) {
49
            throw new IncorrectRuleException('Rule is not defined');
50
        }
51
    }
52
53
    /**
54
     * @param $rule
55
     * @return string
56
     * @throws IncorrectRuleException
57
     */
58
    private static function getRuleClass($rule): string
59
    {
60
        $class = '\\iamsaint\\yml\\validators\\'.$rule[1];
61
62
        if (!class_exists($class)) {
63
            throw new IncorrectRuleException('Validator not found');
64
        }
65
66
        return $class;
67
    }
68
69
    /**
70
     * @param $rule
71
     * @return bool
72
     * @throws IncorrectRuleException
73
     */
74
    private static function isValidRule($rule):bool
75
    {
76
        self::validateArray($rule);
77
        self::validateDefined($rule);
78
        self::validateString($rule);
79
80
        return false;
81
    }
82
83
    /**
84
     * @param $object
85
     * @param $rule
86
     * @throws IncorrectRuleException
87
     */
88
    public static function validate($object, $rule): void
89
    {
90
        if (self::isValidRule($rule)) {
91
            $ruleClass = self::getRuleClass($rule);
92
93
            $attributes = is_array($rule[0]) ? $rule[0] : [$rule[0]];
94
95
            $validator = new $ruleClass();
96
97
            if ($validator instanceof Validator) {
98
                $validator->validate($object, $attributes, $rule[2] ?: []);
99
            }
100
        }
101
    }
102
}
103