Passed
Push — master ( 022aa2...8d4f2f )
by Henri
04:23 queued 47s
created

PrioritizeTrait::getKeyArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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