Passed
Branch master (26b825)
by Henri
01:23
created

CheckWhere::isParameter()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
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(!$this->isParameter($part)){
35
                continue;
36
            }
37
                
38
            $param = substr(str_replace('?','',$part),1,-1);
39
40
            if(array_key_exists($param,$route['where'])){
41
                    
42
                $params[$param] = $route['where'][$param];
43
44
                if(!preg_match("/^{$params[$param]}$/",$request[$p])){
45
                    $pass = false;
46
                }
47
            }
48
        }
49
        
50
        return $pass;
51
    }
52
53
    protected function isParameter(string $part): bool
54
    {
55
        return (substr($part,0,1) === '{' && substr($part,-1) === '}');
56
    }
57
58
    protected function callWhereAdd($data)
59
    {
60
        $this->checkWhereParam($data);
61
        
62
        $data = (count($data) > 1) ? [$data[0] => $data[1]] : $data[0];
63
        
64
        $route = end($this->routers);
65
        $routeURI = explode('/',$route['url']);
66
        $params = [];
67
        foreach($routeURI as $part){
68
            if(!$this->isParameter($part)){
69
                continue;
70
            }
71
            
72
            $param = substr(str_replace('?','',$part),1,-1);
73
74
            if(array_key_exists($param,$data)){
75
                $params[$param] = $data[$param];
76
            }
77
                
78
        }
79
80
        $this->checkWhereParams($params);
81
82
        $route['where'] = (is_array($route['where'])) ? array_merge($route['where'],$params) : $params;
83
84
        $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...
85
    }
86
87
}
88