PrioritizeTrait   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 30
dl 0
loc 61
rs 10
c 2
b 0
f 1
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A orderRoutes() 0 11 3
A sorted() 0 6 2
A getKeyArray() 0 6 2
A sortRoutes() 0 26 4
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace HnrAzevedo\Router;
6
7
trait PrioritizeTrait
8
{
9
    use Helper;
10
11
    protected bool $sorted = false;
12
13
    protected function sorted(?bool $sorted = null): bool
14
    {
15
        if(null !== $sorted) {
16
            $this->sorted = $sorted;
17
        }
18
        return $this->sorted;
19
    }
20
    
21
    protected function sortRoutes(): bool
22
    {
23
        if($this->sorted()) {
24
            return true;
25
        }
26
27
        $staticRoutes = [];
28
        $paramRoutes = [];
29
30
        foreach($this->getRoutes() as $r => $route){
31
32
            $path = urldecode(unserialize($route['uri'])->getPath());
33
34
            if(strstr($path, '{')) {
35
                $paramRoutes[$this->getKeyArray(substr_count($path, '/') + substr_count($path, '{'), $paramRoutes)] = $route;
36
                continue;    
37
            }
38
39
            $staticRoutes[$this->getKeyArray(substr_count($path, '/'), $staticRoutes)] = $route;
40
        }
41
42
        rsort($paramRoutes);
43
        rsort($staticRoutes);
44
45
        $this->orderRoutes(array_merge($staticRoutes, $paramRoutes));
46
        return $this->sorted(true);
47
    }
48
49
    private function getKeyArray(int $index, array $array): int
50
    {
51
        while(array_key_exists($index, $array)){
52
            $index++;
53
        }
54
        return $index;
55
    }
56
57
    private function orderRoutes(array $routes):void
58
    {
59
        $kRoutes = $routes;
60
        foreach($routes as $r => $route){
61
            if(array_key_exists('name', $route)) {
62
                unset($kRoutes[$r]);
63
                $kRoutes["'{$route['name']}'"] = $route;
64
            }
65
        }
66
        ksort($kRoutes);
67
        $this->setRoutes($kRoutes);
68
    }
69
}
70