Passed
Push — master ( 7ae9c9...7f00ee )
by Henri
01:22
created

Validator::hasProvider()   A

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
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 4
rs 10
1
<?php
2
3
namespace HnrAzevedo\Validator;
4
5
use HnrAzevedo\Validator\Rules;
6
use Exception;
7
8
Class Validator{
9
    use Check;
10
11
    public static function add(object $model,callable $return): void
12
    {
13
        self::$model = get_class($model);
14
        self::$validators[self::$model] = $return($Rules = new Rules($model));
15
    }
16
    
17
    private static function existData()
18
    {
19
        if(!array_key_exists('data', self::$data)){
20
            throw new Exception('Informações cruciais não foram recebidas.');
21
        }
22
    }
23
24
    private static function jsonData()
25
    {
26
        if(json_decode(self::$data['data']) === null){
27
            throw new Exception('O servidor recebeu as informações no formato esperado.');
28
        }
29
    }
30
31
    private static function hasProvider()
32
    {
33
        if(!array_key_exists('provider',self::$data)){
34
            throw new Exception('O servidor não recebeu o ID do formulário.');
35
        }
36
    }
37
38
    private static function hasRole()
39
    {
40
        if(!array_key_exists('role',self::$data)){
41
            throw new Exception('O servidor não conseguiu identificar a finalidade deste formulário.');
42
        }
43
    }
44
45
    private static function includeValidations()
46
    {
47
        if( file_exists(VALIDATOR_CONFIG['path'] . ucfirst(self::$data['provider']) . '.php') ){
48
            require_once(VALIDATOR_CONFIG['path'] . ucfirst(self::$data['provider']) . '.php');
49
        }
50
    }
51
52
    private static function getClass(string $class)
53
    {
54
        if(!class_exists($class)){
55
		$class = basename($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[$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 checkDatas()
70
    {
71
		self::existData();
72
        self::jsonData();
73
        self::hasProvider();
74
        self::hasRole();
75
    }
76
77
    public static function execute(array $datas): bool
78
    {
79
        self::$data = $datas;
80
81
        self::checkDatas();
82
            
83
        self::includeValidations();
84
85
        self::$model = get_class(self::getClass('HnrAzevedo\\Validator\\'.ucfirst(self::$data['provider'])));
86
87
		self::existRole(self::$model);
88
            
89
		foreach ( (self::$validators[self::$model]->getRules($datas['role'])) as $key => $value) {
90
            if(@$value['required'] === true){
91
                self::$required[$key] = $value;
92
            }
93
        }
94
95
        self::$errors = [];
96
97
        self::validate();
98
        
99
        self::check_requireds();
100
				
101
		return self::check_errors();
102
    }
103
104
    public static function check_errors(): bool
105
    {
106
        return (count(self::$errors) === 0);
107
    }
108
    
109
    public static function validate()
110
    {
111
        foreach ( (self::$validators[self::$model]->getRules(self::$data['role'])) as $key => $value) {
112
113
			foreach (json_decode(self::$data['data']) as $keyy => $valuee) {
114
115
				if(!array_key_exists($keyy, (self::$validators[self::$model]->getRules(self::$data['role'])) )){
116
                    throw new Exception("O campo '{$keyy}' não é esperado para está operação.");
117
                }
118
119
				if($keyy===$key){
120
121
                    unset(self::$required[$key]);
122
123
					foreach ($value as $subkey => $subvalue) {
124
                        $function = "check_{$subkey}";
125
                        self::testMethod($function);
126
                        self::$function($keyy,$subvalue);
127
					}
128
				}
129
			}
130
        }
131
    }
132
133
    public static function getErrors(): array
134
    {
135
        return self::$errors;
136
    }
137
138
    public static function testMethod($method)
139
    {
140
        if(!method_exists(static::class, $method)){
141
            throw new Exception("{$method} não é uma validação válida.");
142
        }
143
    }
144
145
    public static function toJson(array $request): string
146
    { 
147
        $response = null;
148
149
        self::$data['provider'] = $request['provider'];
150
        self::$data['role'] = $request['role'];
151
152
        self::includeValidations();
153
154
        self::$model = get_class( self::getClass('HnrAzevedo\\Validator\\'.ucfirst($request['provider'])) );
155
156
        self::existRole(self::$model);
157
158
		foreach ( self::$validators[self::$model]->getRules($request['role'])  as $field => $r) {
159
            $r = self::replaceRegex($r);
160
            $response .= ("{$field}:".json_encode(array_reverse($r))).',';
161
        }
162
163
        return '{'.substr($response,0,-1).'}';
164
    }
165
    
166
    private static function replaceRegex(array $rules): array
167
    {
168
        if(array_key_exists('regex',$rules)){ 
169
            $rules['regex'] = substr($rules['regex'],1,-2);
170
        }
171
        return $rules;
172
    }
173
}
174