Passed
Push — master ( c44634...5079d8 )
by Henri
08:48 queued 10s
created

Validator::getInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
c 0
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 Psr\Http\Server\MiddlewareInterface;
0 ignored issues
show
Bug introduced by
The type Psr\Http\Server\MiddlewareInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
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
        self::getInstance()->checkDatas($data);
60
61
        self::$data = $data;
62
63
        $model = self::getInstance()->namespace.'\\'.ucfirst(self::$data['PROVIDER']);
64
            
65
        self::$model = self::getClass($model);
66
67
		self::existRole(self::$model);
68
            
69
		foreach ( (self::$validators[self::$model]->getRules($data['ROLE'])) as $key => $value) {
70
            if(@$value['required'] === true){
71
                self::$required[$key] = $value;
72
            }
73
        }
74
75
        self::$errors = [];
76
77
        self::validate();
78
        
79
        self::checkRequireds();
80
				
81
		return self::checkErrors();
82
    }
83
84
    public static function checkErrors(): bool
85
    {
86
        return (count(self::$errors) === 0);
87
    }
88
    
89
    public static function validate(): void
90
    {
91
        foreach ( (self::$validators[self::$model]->getRules(self::$data['ROLE'])) as $key => $value) {
92
93
			foreach (self::$data as $keyy => $valuee) {
94
95
				if(!array_key_exists($keyy, (self::$validators[self::$model]->getRules(self::$data['ROLE'])) ) && !in_array($keyy,self::getInstance()->defaultData)){
96
                    throw new \RuntimeException("O campo '{$keyy}' não é esperado para está operação.");
97
                }
98
99
				if($keyy===$key){
100
101
                    unset(self::$required[$key]);
102
103
					foreach ($value as $subkey => $subvalue) {
104
                        $function = "check".ucfirst($subkey);
105
                        self::testMethod($function);
106
                        self::$function($keyy,$subvalue);
107
					}
108
				}
109
			}
110
        }
111
    }
112
113
    public static function getErrors(): array
114
    {
115
        return self::$errors;
116
    }
117
118
    public static function testMethod($method)
119
    {
120
        if(!method_exists(static::class, $method)){
121
            throw new \RuntimeException("{$method} não é uma validação válida.");
122
        }
123
    }
124
125
    public static function toJson(array $request): string
126
    { 
127
        $response = null;
128
129
        self::getInstance()->checkDatas($request);
130
131
        self::$data['PROVIDER'] = $request['PROVIDER'];
132
        self::$data['ROLE'] = $request['ROLE'];
133
134
        $model = self::getInstance()->namespace.'\\'.ucfirst($request['PROVIDER']);
135
136
        self::$model = self::getClass($model);
137
138
        self::existRole(self::$model);
139
140
		foreach ( self::$validators[self::$model]->getRules($request['ROLE'])  as $field => $r) {
141
            $r = self::replaceRegex($r);
142
            $response .= ("{$field}:".json_encode(array_reverse($r))).',';
143
        }
144
145
        return '{'.substr($response,0,-1).'}';
146
    }
147
    
148
    private static function replaceRegex(array $rules): array
149
    {
150
        if(array_key_exists('regex',$rules)){ 
151
            $rules['regex'] = substr($rules['regex'],1,-2);
152
        }
153
        return $rules;
154
    }
155
156
    public static function namespace(string $namespace): Validator
157
    {
158
        self::getInstance()->namespace = $namespace;
159
        return self::getInstance();
160
    }
161
}
162