Passed
Push — master ( 42c6c4...6eb781 )
by Henri
06:37
created

Validator::hasMethod()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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