Passed
Push — master ( deef25...536b09 )
by Henri
01:22
created

Check   A

Complexity

Total Complexity 42

Size/Duplication

Total Lines 141
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 51
c 1
b 0
f 0
dl 0
loc 141
rs 9.0399
wmc 42

13 Methods

Rating   Name   Duplication   Size   Complexity  
A check_requireds() 0 4 2
A check_mincount() 0 6 3
A check_regex() 0 10 5
A check_maxlength() 0 10 5
A testArray() 0 6 2
A check_equals() 0 10 4
A check_minlength() 0 9 5
A check_maxcount() 0 6 3
A check_filter() 0 6 3
A check_type() 0 10 4
A check_required() 0 3 2
A toNext() 0 3 2
A validateDate() 0 4 2

How to fix   Complexity   

Complex Class

Complex classes like Check often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Check, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace HnrAzevedo\Validator;
4
5
use Exception;
6
7
Trait Check{
8
    protected static array $data = [];
9
    protected static array $validators = [];
10
    protected static string $model = '';
11
    protected static array $required = [];
12
13
    protected static function check_minlength(string $param, $value)
14
    {
15
        if(self::toNext($param,$value)){    
16
            
17
            $realval = (is_array(json_decode(self::$data['data'])->$param)) ? json_decode(self::$data['data'])->$param : [json_decode(self::$data['data'])->$param];
18
19
            foreach($realval as $val){
20
                if($value > strlen($val)) {
21
                    throw new Exception("{$param} não atingiu o mínimo de caracteres esperado.",1);
22
                }
23
            }
24
        }       
25
    }
26
27
    protected static function check_requireds()
28
    {
29
        if(count(self::$required) > 0){
30
            throw new Exception('As seguintes informações não poderam ser validadas: '.implode(', ',array_keys(self::$required)).'.');
31
        }
32
    }
33
34
    protected static function check_regex(string $param, $value)
35
    {
36
        if(self::toNext($param,$value)){
37
38
            $realval = (is_array(json_decode(self::$data['data'])->$param)) ? json_decode(self::$data['data'])->$param : [json_decode(self::$data['data'])->$param];
39
40
            foreach($realval as $val){
41
42
                if(!preg_match(self::$validators[self::$model]->getRules(self::$data['role'])[$param]['regex'], $val)){
43
                    throw new Exception("{$param} inválido(a).",1);
44
                }  
45
46
            }
47
        }       
48
    }
49
50
    protected static function check_mincount(string $param, $value)
51
    {
52
        if(self::toNext($param,$value)){
53
            $array = self::testArray($param, json_decode(self::$data['data'])->$param);
54
            if(count($array) < $value){
55
                throw new Exception("{$param} não atingiu o mínimo esperado.",1);
56
            }
57
        }
58
    }
59
60
    protected static function check_maxcount(string $param, $value)
61
    {
62
        if(self::toNext($param,$value)){
63
            $array = self::testArray($param, json_decode(self::$data['data'])->$param);
64
            if(count($array) > $value){
65
                throw new Exception("{$param} ultrapassou o esperado.",1);
66
            }
67
        }
68
    }
69
70
    protected static function testArray(string $param, $value): ?array
71
    {
72
        if(!is_array($value)){
73
            throw new Exception("Era esperado um informação em array para {$param}.");
74
        }
75
        return $value;
76
    }
77
78
    protected static function check_equals(string $param, $value)
79
    {
80
        if(self::toNext($param,$value)){
81
82
            if(!array_key_exists($param,json_decode(self::$data['data'],true))){
83
                throw new Exception("O servidor não encontrou a informação '{$value}' para ser comparada a '{$param}'.",1);
84
            }
85
            
86
            if(json_decode(self::$data['data'])->$param != json_decode(self::$data['data'],true)[$value]){
87
                throw new Exception(ucfirst($param).' está diferente de '.ucfirst($value),1);
88
            }
89
90
        }       
91
    }
92
93
    protected static function check_maxlength(string $param, $value)
94
    {
95
        if(self::toNext($param,$value)){
96
97
            $realval = (is_array(json_decode(self::$data['data'])->$param)) ? json_decode(self::$data['data'])->$param : [json_decode(self::$data['data'])->$param];
98
99
            foreach($realval as $val){
100
101
                if($value < strlen($val)) {
102
                    throw new Exception("{$param} ultrapassou o máximo de caracteres esperado.",1);
103
                }
104
            
105
            }
106
        }       
107
    }
108
109
    protected static function check_type(string $param, $value)
110
    {
111
        if(self::toNext($param,$value)){
112
113
            switch ($value) {
114
                case 'date':
115
                    if(!self::validateDate(json_decode(self::$data['data'])->$param , 'd/m/Y')){
116
                        throw new Exception("{$param} não é uma data válida.");
117
                    }
118
                    break;
119
            }
120
        }       
121
    }
122
123
    protected static function check_filter(string $param, $value)
124
    {
125
        if(self::toNext($param,$value)){
126
127
            if(!filter_var(json_decode(self::$data['data'])->$param, $value)){
128
                throw new Exception("{$param} não passou pela filtragem de dados.");
129
            }
130
131
        }
132
    }
133
134
    public static function validateDate($date, $format = 'Y-m-d H:i:s')
135
    {
136
        $d = \DateTime::createFromFormat($format, $date);
137
        return $d && $d->format($format) == $date;
138
    }
139
140
    protected static function check_required(string $param): bool
141
    {
142
        return (array_key_exists('required',self::$validators[self::$model]->getRules(self::$data['role'])[$param]) && self::$validators[self::$model]->getRules(self::$data['role'])[$param]['required']);
143
    }
144
145
    protected static function toNext(string $param, $value)
146
    {
147
        return (self::check_required($param) || strlen($value > 0));
148
    }
149
150
}