Passed
Branch v2-dev (0ddf7c)
by Henri
10:02
created

PrioritizeTrait::sortRoutes()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 11
c 1
b 0
f 1
nc 3
nop 0
dl 0
loc 22
rs 9.9
1
<?php
2
3
namespace HnrAzevedo\Router;
4
5
trait PrioritizeTrait{
6
7
    protected array $routes = [];
8
9
    protected function sortRoutes(): void
10
    {
11
        $staticRoutes = [];
12
        $paramRoutes = [];
13
14
        foreach($this->routes as $r => $route){
15
16
            $path = urldecode($route['uri']->getPath());
17
18
            if(strstr($path,'{')){
19
                $paramRoutes[$this->getKeyArray(substr_count($path,'/') + substr_count($path,'{'),$paramRoutes)] = $route;
20
                continue;    
21
            }
22
23
            $staticRoutes[$this->getKeyArray(substr_count($path,'/'),$staticRoutes)] = $route;
24
25
        }
26
27
        rsort($paramRoutes);
28
        rsort($staticRoutes);
29
30
        $this->orderRoutes(array_merge($staticRoutes,$paramRoutes));
31
    }
32
33
    private function getKeyArray(int $index, array $array): int
34
    {
35
        while(array_key_exists($index,$array)){
36
            $index++;
37
        }
38
        return $index;
39
    }
40
41
    private function orderRoutes(array $routes):void
42
    {
43
        $kRoutes = $routes;
44
        foreach($routes as $r => $route){
45
            if(array_key_exists('name',$route)){
46
                unset($kRoutes[$r]);
47
                $kRoutes[$route['name']] = $route;
48
            }
49
        }
50
        ksort($kRoutes);
51
        $this->routes = $kRoutes;
52
    }
53
}