Passed
Push — master ( 6fd4a6...67aa40 )
by Henri
01:14
created

Validator::validate()   D

Complexity

Conditions 36
Paths 62

Size

Total Lines 101
Code Lines 58

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 36
eloc 58
c 1
b 0
f 0
nc 62
nop 1
dl 0
loc 101
rs 4.1666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace HnrAzevedo\Validator;
4
5
use HnrAzevedo\Validator\Rules;
6
use Exception;
7
8
Class Validator{
9
    
10
    private static array $validators = array();
11
    private static array $data = [];
12
13
    public static function add(object $model,callable $return): void
14
    {
15
        self::$validators[get_class($model)] = $return($Rules = new Rules($model));
16
    }
17
    
18
    private static function existData()
19
    {
20
        if(!array_key_exists('data', self::$data)){
21
            throw new Exception('Informações cruciais não foram recebidas.');
22
        }
23
    }
24
25
    private static function jsonData()
26
    {
27
        if(json_decode(self::$data['data']) === null){
28
            throw new Exception('O servidor recebeu as informações no formato esperado.');
29
        }
30
    }
31
32
    private static function hasProvider()
33
    {
34
        if(!array_key_exists('provider',self::$data)){
35
            throw new Exception('O servidor não recebeu o ID do formulário.');
36
        }
37
    }
38
39
    private static function hasRole()
40
    {
41
        if(!array_key_exists('role',self::$data)){
42
            throw new Exception('O servidor não conseguiu identificar a finalidade deste formulário.');
43
        }
44
    }
45
46
    private static function includeValidations()
47
    {
48
        if( file_exists(VALIDATOR_CONFIG['path'] . ucfirst(self::$data['provider']) . '.php') ){
49
            require_once(VALIDATOR_CONFIG['path'] . ucfirst(self::$data['provider']) . '.php');
50
        }
51
    }
52
53
    private static function getClass(string $class)
54
    {
55
        if(!class_exists($class)){
56
            throw new Exception("Form ID {$class} inválido.");
57
        }
58
59
        return new $class();
60
    }
61
62
    private static function existRole($rules)
63
    {
64
        if(empty(self::$validators[get_class($rules)]->getRules(self::$data['role']))){
65
            throw new Exception('Não existe regras para validar este formulário.');
66
        }
67
    }
68
69
    public static function execute(array $datas): bool
70
    {
71
        self::$data = $datas;
72
73
		self::existData();
74
        self::jsonData();
75
        self::hasProvider();
76
        self::hasRole();
77
		            
78
        $data = (array) json_decode($datas['data']);
0 ignored issues
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
79
            
80
        self::includeValidations();
81
82
        $rules = self::getClass('HnrAzevedo\\Validator\\'.ucfirst(self::$data['provider']));
83
84
		self::existRole($rules);
85
86
		$validators = self::$validators[get_class($rules)]->getRules($datas['role']);
87
88
        $tests = 0;
89
            
90
		foreach ($validators as $key => $value) {
91
		    $tests = (@$value['required'] === true ) ? $tests+1 : $tests;
92
        }
93
94
		$testeds = self::validate($validators);
95
            
96
		if($tests > $testeds){
97
            throw new Exception('Alguma informação necessária não pode ser validada.');
98
        }
99
				
100
		return true;
101
    }
102
    
103
    public static function validate(array $validators): int
104
    {
105
        $validate = 0;
106
        foreach ($validators as $key => $value) {
107
108
			foreach (json_decode(self::$data['data']) as $keyy => $valuee) {
109
110
                $v = $valuee;
111
                    
112
				if(is_array($valuee)){
113
					$v = null;
114
					foreach ($valuee as $vvv) {
115
						$v .= $vvv;
116
					}
117
                }
118
                    
119
				$valuee = $v;
120
121
				if(!array_key_exists($keyy, $validators)){
122
                    throw new Exception("O campo '{$keyy}' não é esperado para está operação.");
123
                }
124
125
				if($keyy===$key){
126
127
                    $validate++;
128
                        
129
					foreach ($value as $subkey => $subvalue) {
130
131
						switch ($subkey) {
132
							case 'minlength':
133
                                if(array_key_exists('required', $value)){
134
                                    if($value['required'] or strlen($valuee)!==0){
135
                                        if(strlen($valuee)===0){
136
                                            throw new Exception("O campo '{$key}' é obrigatório.",1);
137
                                        }
138
                                         
139
                                        if(strlen($valuee) < (int) $subvalue){
140
                                            throw new Exception("{$key} não atingiu o mínimo de caracteres esperado.",1);
141
                                        }
142
                                    }
143
                                }
144
                                break;
145
146
                            case 'type':
147
                                if(array_key_exists('required', $value)){
148
                                    if($value['required'] or strlen($valuee)!==0){
149
                                        switch ($subvalue) {
150
                                            case 'date':
151
                                                $date = explode('/', $valuee);
152
                                                if(count($date) != 3){
153
                                                    throw new Exception('Data inválida.',1);
154
                                                }
155
                                                if(! checkdate( intval($date[1]), intval($date[0]), intval($date[2]) )){
156
                                                    throw new Exception('Data inválida.',1);
157
                                                }
158
                                                break;
159
                                        }
160
                                    }
161
                                }
162
    						    break;
163
164
							case 'maxlength':
165
                                if(array_key_exists('required', $value)){
166
                                    if($value['required'] or strlen($valuee)!==0){
167
                                        if(strlen($valuee)>(int)$subvalue){
168
                                            throw new Exception("{$key} ultrapassou o limite de caracteres permitidos.",1);
169
                                        }
170
                                    }
171
                                }
172
                                break;
173
174
							case 'regex':
175
                                if(array_key_exists('required', $value)){
176
                                    if($value['required'] or strlen($valuee)!==0){
177
                                        if(!@preg_match($subvalue,$valuee)){
178
                                            throw new Exception("{$key} inválido(a).",1);
179
                                        }
180
                                    }
181
                                }
182
                                break;
183
184
							case 'equals':
185
                                $equals = false;
186
                                foreach (self::$data as $ke => $sub) {
187
                                    if($ke===$subvalue){
188
                                        $equals=true;
189
                                        if($valuee !== $sub){
190
                                            throw new Exception(ucfirst($key).' está diferente de '.ucfirst($ke),1);
191
                                        }
192
                                    }
193
                                }
194
                                if(!$equals){
195
                                    throw new Exception("O servidor não encontrou a informação '{$subvalue}' para ser comparada a '{$key}'.",1);
196
                                }
197
                                break;
198
	    				}
199
					}
200
				}
201
			}
202
        }
203
        return $validate;
204
    }
205
206
    public static function toJson(array $request): string
207
    {
208
        self::$data['provider'] = $request['provider'];
209
210
        self::includeValidations();
211
212
        $rules = self::getClass('HnrAzevedo\\Validator\\'.ucfirst($request['provider']));
213
		
214
		self::existRole($rules);
215
		
216
        /* For function to validate information in javascript */
217
        $response = '{';
218
219
		foreach ( self::$validators[get_class($rules)]->getRules($request['role'])  as $field => $r) {
220
            $response .= $field.':{';
221
                
222
			foreach(array_reverse($r) as $rule => $value){
223
                $value = (gettype($value)==='string') ? '\''.$value.'\'' : $value;
224
                
225
				if(gettype($value)==='boolean'){
226
                    $value = ($value) ? 'true' : 'false';
227
                }
228
229
                $value = ($rule=='regex') ? str_replace('\\','\\\\','\''.substr($value,2,strlen($value)-4).'\'') : $value;
230
                
231
				$response .= $rule.':'.$value.',';
232
            }
233
            
234
			$response .='},';
235
        }
236
237
		return substr(str_replace(',}','}',$response),0,-1).'}';
238
	}
239
}
240