Passed
Push — master ( deef25...536b09 )
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
            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 true;
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
                        $function = "check_{$subkey}";
117
118
                        self::testMethod($function);
119
120
                        self::$function($keyy,$subvalue);
121
					}
122
				}
123
			}
124
        }
125
    }
126
127
    public static function testMethod($method)
128
    {
129
        if(!method_exists(static::class, $method)){
130
            throw new Exception("{$method} não é uma validação válida.");
131
        }
132
    }
133
134
    public static function toJson(array $request): string
135
    { 
136
        $response = null;
137
138
        self::$data['provider'] = $request['provider'];
139
        self::$data['role'] = $request['role'];
140
141
        self::includeValidations();
142
143
        self::$model = get_class( self::getClass('HnrAzevedo\\Validator\\'.ucfirst($request['provider'])) );
144
145
        self::existRole(self::$model);
146
147
		foreach ( self::$validators[self::$model]->getRules($request['role'])  as $field => $r) {
148
            
149
            $response .= ("{$field}:".json_encode(array_reverse($r))).',';
150
            
151
        }
152
153
        $response = '{'.substr($response,0,-1).'}';
154
        $response = str_replace(',"',',',$response);
155
        $response = str_replace('{"','',$response);
156
        $response = str_replace('":',':',$response);
157
158
		return $response;
159
	}
160
}
161