forked from xyluz/hng.tech
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.php
79 lines (78 loc) · 1.89 KB
/
router.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
class Router
{
/**
* An array of the routes keyed by URI.
*
* @var array
*/
protected $routes = [];
/**
* An array of view paths to search for views.
*
* @var array
*/
protected $viewPaths = [
'',
'interns/'
];
/**
* Create an instance of the router.
*
* @return void;
*/
public function __construct()
{
$this->basePath = __DIR__ . DIRECTORY_SEPARATOR;
}
/**
* Add a route to the routes collection.
*
* @param array|string $url
* @param string|null $view
* @return this
*/
public function add($url, $view = null)
{
if (func_num_args() === 1 && is_array($url)) {
foreach ($url as $path => $view) {
$this->routes[$path] = $view;
}
return $this;
}
$this->routes[$url] = $view;
return $this;
}
/**
* Find the route that match the request url.
*
* @param string $url
* @return string
*/
public function match($url)
{
// We'll first look through the list of defined routes
// and if there's a match, we'll just return that, otherwise,
// we'll search through the viewpaths to look for a view matching the
// route.
if (isset($this->routes[$url])) {
return $this->getViewPath().$this->routes[$url];
}
preg_match('/(.*\/(.*))/', $url, $matches);
foreach ($this->viewPaths as $path) {
if (@file_exists($matchedPath = $this->getViewPath($path).$path.end($matches).'.php')) {
return $matchedPath;
}
}
return $this->getViewPath().'404.php';
}
/**
* Get the path to the views.
*
* @return string
*/
protected function getViewPath()
{
return $this->basePath.'views/';
}
}