Passed
Branch master (481374)
by Henri
03:04 queued 01:44
created

Validator::getErrors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
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::validate();
95
        
96
        self::check_requireds();
97
				
98
		return self::check_errors();
99
    }
100
    
101
    public static function validate()
102
    {
103
        foreach ( (self::$validators[self::$model]->getRules(self::$data['role'])) as $key => $value) {
104
105
			foreach (json_decode(self::$data['data']) as $keyy => $valuee) {
106
107
				if(!array_key_exists($keyy, (self::$validators[self::$model]->getRules(self::$data['role'])) )){
108
                    throw new Exception("O campo '{$keyy}' não é esperado para está operação.");
109
                }
110
111
				if($keyy===$key){
112
113
                    unset(self::$required[$key]);
114
115
					foreach ($value as $subkey => $subvalue) {
116
                        try{
117
                            $function = "check_{$subkey}";
118
                            self::testMethod($function);
119
                            self::$function($keyy,$subvalue);
120
                        }catch(Exception $exception){
121
                            self::$errors[] = $exception->getMessage();
122
                        }
123
                        
124
					}
125
				}
126
			}
127
        }
128
    }
129
130
    public static function getErrors(): array
131
    {
132
        return self::$errors;
133
    }
134
135
    public static function testMethod($method)
136
    {
137
        if(!method_exists(static::class, $method)){
138
            throw new Exception("{$method} não é uma validação válida.");
139
        }
140
    }
141
142
    public static function toJson(array $request): string
143
    { 
144
        $response = null;
145
146
        self::$data['provider'] = $request['provider'];
147
        self::$data['role'] = $request['role'];
148
149
        self::includeValidations();
150
151
        self::$model = get_class( self::getClass('HnrAzevedo\\Validator\\'.ucfirst($request['provider'])) );
152
153
        self::existRole(self::$model);
154
155
		foreach ( self::$validators[self::$model]->getRules($request['role'])  as $field => $r) {
156
            
157
            $response .= ("{$field}:".json_encode(array_reverse($r))).',';
158
            
159
        }
160
161
        $response = '{'.substr($response,0,-1).'}';
162
        $response = str_replace(',"',',',$response);
163
        $response = str_replace('{"','',$response);
164
        $response = str_replace('":',':',$response);
165
166
		return $response;
167
	}
168
}
169