Passed
Push — master ( edfa92...5471a5 )
by Radu
01:32
created

Router   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 63
rs 10
c 0
b 0
f 0
wmc 15

2 Methods

Rating   Name   Duplication   Size   Complexity  
C getRoute() 0 34 8
C parseCustomRoutes() 0 25 7
1
<?php
2
namespace WebServCo\Framework\Libraries;
3
4
final class Router extends \WebServCo\Framework\AbstractLibrary
5
{
6
    public function getRoute($requestCustom, $routes, $extraArgs = [])
7
    {
8
        $routeString = $this->parseCustomRoutes($requestCustom, $routes);
9
        if (empty($routeString) || 'index' == $routeString) {
10
            $defaultRoute = $this->setting('default_route');
11
            if (!isset($defaultRoute[1])) {
12
                throw new \WebServCo\Framework\Exceptions\ApplicationException(
13
                    "Default route missing or not valid"
14
                );
15
            }
16
            return $defaultRoute;
17
        }
18
        
19
        $parts = explode('/', $routeString, 3);
20
21
        if (empty($parts[1])) {
22
            throw new \WebServCo\Framework\Exceptions\NotFoundException(
23
                sprintf('The requested resource "%s" was not found', $routeString)
24
            );
25
        }
26
27
        $controller = $parts[0];
28
        $action = $parts[1];
29
        $args = [];
30
        
31
        if (!empty($parts['2'])) {
32
            $args = explode('/', $parts[2]);
33
        }
34
        if (!empty($extraArgs)) {
35
            foreach ($extraArgs as $k => $v) {
36
                $args[] = $v;
37
            }
38
        }
39
        return [$controller, $action, $args];
40
    }
41
    
42
    private function parseCustomRoutes($requestCustom, $routes)
43
    {
44
        if (is_array($routes)) {
45
            foreach ($routes as $k => $v) {
46
                 $k = str_replace(['{num}','{any}'], ['[0-9]+','.+'], $k);
47
                 /**
48
                  * Check for a custom route match.
49
                  */
50
                if (preg_match("#^{$k}$#", $requestCustom) ||
51
                preg_match("#^{$k}/$#", $requestCustom)
52
                ) {
53
                    /**
54
                     * Check for back references.
55
                     */
56
                    if (false !== strpos($v, '$') && false !== strpos($k, '(')) {
57
                        /**
58
                         * Parse request.
59
                         */
60
                         $v = preg_replace("#^{$k}$#", $v, $requestCustom);
61
                    }
62
                    return $v;
63
                }
64
            }
65
        }
66
        return $requestCustom;
67
    }
68
}
69