Passed
Push — master ( 3d96d8...b2d9fe )
by Henri
01:28
created

Validator::testMethod()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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