route::match()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4.026

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 15
cts 17
cp 0.8824
rs 9.52
c 0
b 0
f 0
cc 4
nc 3
nop 2
crap 4.026
1
<?php
2
3
namespace arc;
4
/**
5
 * Class route
6
 * A simple router.
7
 * @package arc
8
 */
9
class route {
10
11
    /**
12
     * Matches a path or url to a list of routes and calls the best matching route handler.
13
     * @param string $path
14
     * @param mixed $routes A tree of routes with handlers as nodeValue.
15
     * @return array|bool
16
     */
17 4
    public static function match($path, $routes) {
18 4
        $routes     = \arc\tree::expand($routes);
19 4
        $controller = \arc\tree::dive(
20 4
            $routes->cd($path),
21 4
            function($node) {
22 4
                if ( isset($node->nodeValue) ) {
23 4
                    return $node;
24
                }
25 4
            }
26
        );
27 4
        if ( $controller ) {
28 4
            $remainder = substr( $path, strlen($controller->getPath()) );
29 4
            if ( is_callable($controller->nodeValue) ) {
30 4
                $result = call_user_func($controller->nodeValue, $remainder);
31
            } else {
32
                $result = $controller->nodeValue;
33
            }
34
            return [
35 4
                'path' => $controller->getPath(),
36 4
                'remainder' => $remainder,
37 4
                'result' => $result
38
            ];
39
        }
40
        return false;
41
    }
42
43
}