Passed
Push — main ( 1a3a01...f6a128 )
by Moises
01:22
created

Route::setParam()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 5
nc 3
nop 2
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace DevPontes\Route;
4
5
use DevPontes\Route\Traits\Matcher;
6
use DevPontes\Route\Exception\ErrorRoute;
7
8
/**
9
 * Description of Route
10
 *
11
 * @author Moises Pontes
12
 * @package DevPontes\Route
13
 */
14
class Route
15
{
16
    use Matcher;
17
18
    /** @var ErrorRoute */
19
    private $fail;
20
21
    /** @var string */
22
    private $param;
23
24
    /** @var string */
25
    private $namespace;
26
27
    /** @var array */
28
    private $url;
29
30
    /** @var array */
31
    private $routes = [];
32
33
    /**
34
     * Route constructor.
35
     *
36
     * @param array $routes
37
     * @param array $error
38
     */
39
    public function __construct(array $routes)
40
    {
41
        $url = filter_input(INPUT_GET, 'url', FILTER_SANITIZE_SPECIAL_CHARS);
42
43
        $this->setUrl($url);
44
        $this->setRoutes($routes);
45
    }
46
47
    /**
48
     * @return ErrorRoute|null
49
     */
50
    public function fail(): ?ErrorRoute
51
    {
52
        return $this->fail;
53
    }
54
55
    /**
56
     * Set namespace app
57
     *
58
     * @param string $namespace
59
     * @return Route
60
     */
61
    public function namespace(string $namespace): Route
62
    {
63
        $this->namespace = $namespace;
64
        return $this;
65
    }
66
67
    /**
68
     * Separate the URL
69
     *
70
     * @param string|null $url
71
     * @return void
72
     */
73
    private function setUrl(?string $url): void
74
    {
75
        $url = "/" . $url;
76
        $this->url = explode('/', $url);
77
    }
78
79
    /**
80
     * Config the routes
81
     *
82
     * @param array $routes
83
     * @return void
84
     */
85
    private function setRoutes(array $routes): void
86
    {
87
        foreach ($routes as $route) {
88
            $action = explode('@', $route[1]);
89
            $url = preg_replace('/\{[^}]+\}/', '{}', $route[0]);
90
            $this->routes[] = new Router($url, $action[1], $action[0]);
91
        }
92
    }
93
94
    /**
95
     * Run route
96
     *
97
     * @return void
98
     */
99
    public function run(): void
100
    {
101
        try {
102
            $router = $this->match($this->url);
103
104
            if (empty($router)) {
105
                throw new ErrorRoute("Page not found", 404);
106
            } else {
107
                $router->execute($this->namespace, $this->param);
108
            }
109
        } catch (ErrorRoute $err) {
110
            $this->fail = $err;
111
        }
112
    }
113
}
114