Passed
Branch master (8a6de3)
by Henri
02:08 queued 48s
created

CheckWhere::callWhereAdd()   A

Complexity

Conditions 6
Paths 12

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 13
c 0
b 0
f 0
nc 12
nop 1
dl 0
loc 24
rs 9.2222
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 checkExistParam($param, $data)
17
    {
18
        if(!array_key_exists($param,$data)){
19
            throw new Exception('Test parameter not available on the route in question.');
20
        }
21
    }
22
23
    protected function checkWhereParams($params)
24
    {
25
        if(count($params) === 0){
26
            throw new Exception('The route in question has no parameters to be tested.');
27
        }
28
    }
29
30
    protected function checkWhere($route, $request): bool
31
    {
32
        $pass = true;
33
34
        if(!is_array($route['where'])){
35
            return $pass;
36
        }
37
38
        $routeURI = explode('/',$route['url']);
39
        $params = [];
40
        foreach($routeURI as $p => $part){
41
            if(substr($part,0,1) === '{' && substr($part,-1) === '}'){
42
                $param = substr($part,1,-1);
43
                $params[$param] = $route['where'][$param];
44
45
                if(!preg_match("/^{$params[$param]}$/",$request[$p])){
46
                    $pass = false;
47
                }
48
            }
49
        }
50
        
51
        return $pass;
52
    }
53
54
    protected function callWhereAdd($data)
55
    {
56
        $this->checkWhereParam($data);
57
        
58
        $data = (count($data) > 1) ? [$data[0] => $data[1]] : $data[0];
59
        
60
        $route = end($this->routers);
61
        $routeURI = explode('/',$route['url']);
62
        $params = [];
63
        foreach($routeURI as $part){
64
            if(substr($part,0,1) === '{' && substr($part,-1) === '}'){
65
                $param = substr($part,1,-1);
66
67
                $this->checkExistParam($param,$data);
68
69
                $params[$param] = $data[$param];
70
            }
71
        }
72
73
        $this->checkWhereParams($params);
74
75
        $route['where'] = (is_array($route['where'])) ? array_merge($route['where'],$params) : $params;
76
77
        $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...
78
    }
79
80
}
81