Passed
Branch v2-dev (f4944f)
by Henri
01:22
created

WhereTrait::matchParam()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 3
c 0
b 0
f 0
nc 3
nop 3
dl 0
loc 5
rs 10
1
<?php
2
3
namespace HnrAzevedo\Router;
4
5
trait WhereTrait
6
{
7
    use Helper;
8
9
    public static function where(array $wheres): Router
10
    {
11
        $route = self::getInstance()->inSave();
12
        $route['where'] = (is_array($route['where'])) ? array_merge($route['where'],$wheres) : $wheres;
13
        self::getInstance()->updateRoute($route,array_key_last(self::getInstance()->routes));
0 ignored issues
show
Bug introduced by
The property routes is declared protected in HnrAzevedo\Router\Router and cannot be accessed from this context.
Loading history...
14
        return self::getInstance();
15
    }
16
17
    protected function checkData(array $route, string $uriPath): void
18
    {
19
        $this->checkCount($route['uri']->getPath(), $uriPath);
20
21
        $uriPath .= (substr($uriPath,strlen($uriPath)-1) !== '/') ? '/' : '';
22
23
        $routePath = explode('/',urldecode($route['uri']->getPath()));
24
        unset($routePath[0]);
25
        $uriPath = explode('/',urldecode($uriPath));
26
        unset($uriPath[0]);
27
28
        $corretRoute = true;
29
        foreach($routePath as $r => $routeFrag){
30
            $where = is_array($route['where']) ? $route['where'] : [];
31
            $routeFrag = $this->replaceParam($where, $routeFrag, $uriPath[$r]);
32
33
            if($routeFrag !== $uriPath[$r]){
34
                $corretRoute = false;
35
            }
36
        }
37
38
        if(!$corretRoute){
39
            throw new \Exception('continue');
40
        }
41
    }
42
43
    private function replaceParam(array $where, string $ref, string $value): string
44
    {
45
        if(((substr($ref,0,1) === '{') && (substr($ref,strlen($ref)-1) === '}'))) {
46
            if(array_key_exists(str_replace(['{','}',':'],'',$ref),$where)){
47
                $this->matchParam($where, $ref, $value);
48
            }
49
            return $value;
50
        } 
51
        return $ref;
52
    }
53
54
    private function checkCount(string $routePath, string $uriPath): void
55
    {
56
        $countRequest = substr_count($uriPath,'/') - substr_count($routePath,'{:');
57
        $countRoute = substr_count($routePath,'/') - substr_count($routePath,'{:');
58
59
        if($countRequest !== $countRoute){
60
            throw new \Exception('continue');
61
        }
62
    }
63
64
    private function matchParam(array $where, string $ref, string $value): void
65
    {
66
        if(substr($ref,0,2) === '{:' || $value !== ''){
67
            if(!preg_match("/^{$where[str_replace(['{','}',':'],'',$ref)]}$/",$value)){
68
                throw new \Exception('continue');
69
            }
70
        }
71
    }
72
73
}
74