Passed
Branch master (dfe554)
by Henri
01:14
created

CheckWhere::checkExistParam()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 2
c 1
b 0
f 1
nc 2
nop 2
dl 0
loc 4
rs 10
1
<?php
2
3
namespace HnrAzevedo\Router;
4
5
use Exception;
6
7
trait CheckWhere{
8
        
9
    protected function checkWhereParam($data)
10
    {
11
        if(count($data) === 0){
12
            throw new Exception('It is necessary to define a condition to be tested.');
13
        }
14
    }
15
16
    protected function checkWhereParams($params)
17
    {
18
        if(count($params) === 0){
19
            throw new Exception('The route in question has no parameters to be tested.');
20
        }
21
    }
22
23
    protected function checkWhere($route, $request): bool
24
    {
25
        $pass = true;
26
27
        if(!is_array($route['where'])){
28
            return $pass;
29
        }
30
31
        $routeURI = explode('/',$route['url']);
32
        $params = [];
33
        foreach($routeURI as $p => $part){
34
            if(substr($part,0,1) === '{' && substr($part,-1) === '}'){
35
                $param = substr(str_replace('?','',$part),1,-1);
36
37
                if(array_key_exists($param,$route['where'])){
38
                    
39
                    $params[$param] = $route['where'][$param];
40
41
                    if(!preg_match("/^{$params[$param]}$/",$request[$p])){
42
                        $pass = false;
43
                    }
44
                }
45
                
46
            }
47
        }
48
        
49
        return $pass;
50
    }
51
52
    protected function callWhereAdd($data)
53
    {
54
        $this->checkWhereParam($data);
55
        
56
        $data = (count($data) > 1) ? [$data[0] => $data[1]] : $data[0];
57
        
58
        $route = end($this->routers);
59
        $routeURI = explode('/',$route['url']);
60
        $params = [];
61
        foreach($routeURI as $part){
62
            if(substr($part,0,1) === '{' && substr($part,-1) === '}'){
63
                $param = substr(str_replace('?','',$part),1,-1);
64
65
                if(array_key_exists($param,$data)){
66
                    $params[$param] = $data[$param];
67
                }
68
                
69
            }
70
        }
71
72
        $this->checkWhereParams($params);
73
74
        $route['where'] = (is_array($route['where'])) ? array_merge($route['where'],$params) : $params;
75
76
        $this->routers[count($this->routers)-1] = $route;
0 ignored issues
show
Bug Best Practice introduced by
The property routers does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
77
    }
78
79
}
80