Passed
Push — master ( b516d9...1b6422 )
by Henri
01:24
created

Validator::testMethod()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
cc 2
eloc 2
c 2
b 0
f 2
nc 2
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
namespace HnrAzevedo\Validator;
4
5
use HnrAzevedo\Validator\Rules;
6
use Psr\Http\Server\MiddlewareInterface;
7
8
Class Validator implements MiddlewareInterface
9
{
10
    use Check, MiddlewareTrait;
11
12
    private static Validator $instance;
13
    private string $namespace = '';
14
    private array $defaultData = [
15
        'REQUEST_METHOD',
16
        'PROVIDER',
17
        'ROLE'
18
    ];
19
20
    private static function getInstance(): Validator
21
    {
22
        self::$instance = (isset(self::$instance)) ? self::$instance : new self();
23
        return self::$instance;
24
    }
25
26
    public static function add(object $model,callable $return): void
27
    {
28
        self::$model = get_class($model);
29
        self::$validators[self::$model] = $return(new Rules($model));
30
    }
31
32
    private static function getClass(string $class)
33
    {
34
        if(!class_exists($class)){
35
            throw new \RuntimeException("Form ID {$class} inválido");
36
        }
37
38
        $class = get_class(new $class());
39
40
        return $class;
41
    }
42
43
    private static function existRole($rules)
44
    {
45
        if(empty(self::$validators[$rules]->getRules(self::$data['ROLE']))){
46
            throw new \RuntimeException('Não existe regras para validar este formulário');
47
        }
48
    }
49
50
    public function checkDatas(array $data): void
51
    {
52
        if(!isset($data['PROVIDER']) || !isset($data['ROLE'])){
53
            throw new \RuntimeException('The server did not receive the information needed to retrieve the requested validator');
54
        }
55
    }
56
57
    public static function execute(array $data): bool
58
    {
59
        try{
60
            self::getInstance()->checkDatas($data);
61
62
            self::$data = $data;
63
64
            $model = self::getInstance()->namespace.'\\'.ucfirst(self::$data['PROVIDER']);
65
                
66
            self::$model = self::getClass($model);
67
68
            self::existRole(self::$model);
69
                
70
            foreach ( (self::$validators[self::$model]->getRules($data['ROLE'])) as $key => $value) {
71
                if(@$value['required'] === true){
72
                    self::$required[$key] = $value;
73
                }
74
            }
75
76
            self::$errors = [];
77
        
78
            self::validate();
79
            self::checkRequireds();
80
        }catch(\Exception $er){
81
            self::$errors[] = $er->getMessage();
82
        }
83
        
84
		return self::checkErrors();
85
    }
86
87
    public static function checkErrors(): bool
88
    {
89
        return (count(self::$errors) === 0);
90
    }
91
    
92
    public static function validate(): void
93
    {
94
        foreach ( (self::$validators[self::$model]->getRules(self::$data['ROLE'])) as $key => $value) {
95
96
			foreach (self::$data as $keyy => $valuee) {
97
98
				self::checkExpected($keyy);
99
100
				if($keyy===$key){
101
102
                    unset(self::$required[$key]);
103
104
					foreach ($value as $subkey => $subvalue) {
105
                        $function = "check".ucfirst($subkey);
106
                        self::testMethod($function);
107
                        self::$function($keyy,$subvalue);
108
					}
109
				}
110
			}
111
        }
112
    }
113
114
    private static function checkExpected(string $keyy): void
115
    {
116
        if(!array_key_exists($keyy, (self::$validators[self::$model]->getRules(self::$data['ROLE'])) ) && !in_array($keyy,self::getInstance()->defaultData)){
117
            throw new \RuntimeException("O campo '{$keyy}' não é esperado para está operação");
118
        }
119
    }
120
121
    public static function getErrors(): array
122
    {
123
        return self::$errors;
124
    }
125
126
    public static function testMethod($method)
127
    {
128
        if(!method_exists(static::class, $method)){
129
            throw new \RuntimeException("{$method} não é uma validação válida");
130
        }
131
    }
132
133
    public static function toJson(array $request): string
134
    { 
135
        $response = null;
136
137
        self::getInstance()->checkDatas($request);
138
139
        self::$data['PROVIDER'] = $request['PROVIDER'];
140
        self::$data['ROLE'] = $request['ROLE'];
141
142
        $model = self::getInstance()->namespace.'\\'.ucfirst($request['PROVIDER']);
143
144
        self::$model = self::getClass($model);
145
146
        self::existRole(self::$model);
147
148
		foreach ( self::$validators[self::$model]->getRules($request['ROLE'])  as $field => $r) {
149
            $r = self::replaceRegex($r);
150
            $response .= ("{$field}:".json_encode(array_reverse($r))).',';
151
        }
152
153
        return '{'.substr($response,0,-1).'}';
154
    }
155
    
156
    private static function replaceRegex(array $rules): array
157
    {
158
        if(array_key_exists('regex',$rules)){ 
159
            $rules['regex'] = substr($rules['regex'],1,-2);
160
        }
161
        return $rules;
162
    }
163
164
    public static function namespace(string $namespace): Validator
165
    {
166
        self::getInstance()->namespace = $namespace;
167
        return self::getInstance();
168
    }
169
}
170