Passed
Branch master (9353c8)
by Henri
02:26 queued 01:07
created

Validator::check_errors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
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
            throw new Exception("Form ID {$class} inválido.");
56
        }
57
58
        return new $class();
59
    }
60
61
    private static function existRole($rules)
62
    {
63
        if(empty(self::$validators[$rules]->getRules(self::$data['role']))){
64
            throw new Exception('Não existe regras para validar este formulário.');
65
        }
66
    }
67
68
    public static function checkDatas()
69
    {
70
		self::existData();
71
        self::jsonData();
72
        self::hasProvider();
73
        self::hasRole();
74
    }
75
76
    public static function execute(array $datas): bool
77
    {
78
        self::$data = $datas;
79
80
        self::checkDatas();
81
            
82
        self::includeValidations();
83
84
        self::$model = get_class(self::getClass('HnrAzevedo\\Validator\\'.ucfirst(self::$data['provider'])));
85
86
		self::existRole(self::$model);
87
            
88
		foreach ( (self::$validators[self::$model]->getRules($datas['role'])) as $key => $value) {
89
            if(@$value['required'] === true){
90
                self::$required[$key] = $value;
91
            }
92
        }
93
94
        self::$errors = [];
95
96
        self::validate();
97
        
98
        self::check_requireds();
99
				
100
		return self::check_errors();
101
    }
102
103
    public static function check_errors(): bool
104
    {
105
        return (count(self::$errors) === 0);
106
    }
107
    
108
    public static function validate()
109
    {
110
        foreach ( (self::$validators[self::$model]->getRules(self::$data['role'])) as $key => $value) {
111
112
			foreach (json_decode(self::$data['data']) as $keyy => $valuee) {
113
114
				if(!array_key_exists($keyy, (self::$validators[self::$model]->getRules(self::$data['role'])) )){
115
                    throw new Exception("O campo '{$keyy}' não é esperado para está operação.");
116
                }
117
118
				if($keyy===$key){
119
120
                    unset(self::$required[$key]);
121
122
					foreach ($value as $subkey => $subvalue) {
123
                        $function = "check_{$subkey}";
124
                        self::testMethod($function);
125
                        self::$function($keyy,$subvalue);
126
					}
127
				}
128
			}
129
        }
130
    }
131
132
    public static function getErrors(): array
133
    {
134
        return self::$errors;
135
    }
136
137
    public static function testMethod($method)
138
    {
139
        if(!method_exists(static::class, $method)){
140
            throw new Exception("{$method} não é uma validação válida.");
141
        }
142
    }
143
144
    public static function toJson(array $request): string
145
    { 
146
        $response = null;
147
148
        self::$data['provider'] = $request['provider'];
149
        self::$data['role'] = $request['role'];
150
151
        self::includeValidations();
152
153
        self::$model = get_class( self::getClass('HnrAzevedo\\Validator\\'.ucfirst($request['provider'])) );
154
155
        self::existRole(self::$model);
156
157
		foreach ( self::$validators[self::$model]->getRules($request['role'])  as $field => $r) {
158
            
159
            $response .= ("{$field}:".json_encode(array_reverse($r))).',';
160
            
161
        }
162
163
        $response = '{'.substr($response,0,-1).'}';
164
        $response = str_replace(',"',',',$response);
165
        $response = str_replace('{"','',$response);
166
        $response = str_replace('":',':',$response);
167
168
		return $response;
169
	}
170
}
171