Passed
Branch master (444b60)
by Henri
02:18 queued 54s
created

Controller::ValidateData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 9
rs 10
cc 3
nc 3
nop 0
1
<?php
2
3
namespace HnrAzevedo\Router;
4
5
use HnrAzevedo\Validator\Validator;
6
use Exception;
7
8
class Controller{
9
    use Helper;
0 ignored issues
show
Bug introduced by
The trait HnrAzevedo\Router\Helper requires the property $routers which is not provided by HnrAzevedo\Router\Controller.
Loading history...
10
11
    protected array $fail = [];
12
13
    private function check_method(string $method): void
14
    {
15
        if(!method_exists($this,$method)){
16
            throw new Exception("{$method} not found in ".get_class($this).".");
17
        }
18
    }
19
20
    public function method(): bool
21
    {        
22
        $this->ValidateData();
23
24
        if($this->check_failData()){
25
            return false;
26
        }
27
28
        $method = $this->getData()['POST']['role'];
29
30
        $this->check_method($method);
31
32
        $this->$method();
33
34
        return true;
35
    }
36
37
    private function ValidateData(): void
38
    {
39
        $valid = Validator::execute($this->getData()['POST']['data']);
40
41
        if(!$valid){
42
            foreach(Validator::getErrors() as $err => $message){
43
                $this->fail[] = [
44
                    'input' => array_keys($message)[0],
45
                    'message' => $message[array_keys($message)[0]]
46
                ]; 
47
            }
48
        }
49
    }
50
51
    private function check_failData(): bool
52
    {
53
        if(count($this->fail) > 0 ){
54
            echo json_encode([
55
                'error'=> $this->fail
56
            ]);
57
        }
58
        return (count($this->fail) > 0 );
59
    }
60
61
}