-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.php
114 lines (85 loc) · 3.09 KB
/
index.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
class Route {
private function simpleRoute($file, $route){
//replacing first and last forward slashes
//$_REQUEST['uri'] will be empty if req uri is /
if(!empty($_REQUEST['uri'])){
$route = preg_replace("/(^\/)|(\/$)/","",$route);
$reqUri = preg_replace("/(^\/)|(\/$)/","",$_REQUEST['uri']);
}else{
$reqUri = "/";
}
if($reqUri == $route){
$params = [];
include($file);
exit();
}
}
function add($route,$file){
//will store all the parameters value in this array
$params = [];
//will store all the parameters names in this array
$paramKey = [];
//finding if there is any {?} parameter in $route
preg_match_all("/(?<={).+?(?=})/", $route, $paramMatches);
//if the route does not contain any param call simpleRoute();
if(empty($paramMatches[0])){
$this->simpleRoute($file,$route);
return;
}
//setting parameters names
foreach($paramMatches[0] as $key){
$paramKey[] = $key;
}
//replacing first and last slashes
//$_REQUEST['uri'] will be empty if req uri is /
if(!empty($_REQUEST['uri'])){
$route = preg_replace("/(^\/)|(\/$)/","",$route);
$reqUri = preg_replace("/(^\/)|(\/$)/","",$_REQUEST['uri']);
}else{
$reqUri = "/";
}
//exploding route address
$uri = explode("/", $route);
//will store index number where {?} parameter is required in the $route
$indexNum = [];
//storing index number, where {?} parameter is required with the help of regex
foreach($uri as $index => $param){
if(preg_match("/{.*}/", $param)){
$indexNum[] = $index;
}
}
//exploding request uri string to array to get
//the exact index number value of parameter from $_REQUEST['uri']
$reqUri = explode("/", $reqUri);
//running for each loop to set the exact index number with reg expression
//this will help in matching route
foreach($indexNum as $key => $index){
//in case if req uri with param index is empty then return
//because url is not valid for this route
if(empty($reqUri[$index])){
return;
}
//setting params with params names
$params[$paramKey[$key]] = $reqUri[$index];
//this is to create a regex for comparing route address
$reqUri[$index] = "{.*}";
}
//converting array to sting
$reqUri = implode("/",$reqUri);
//replace all / with \/ for reg expression
//regex to match route is ready !
$reqUri = str_replace("/", '\\/', $reqUri);
//now matching route with regex
if(preg_match("/$reqUri/", $route))
{
include($file);
exit();
}
}
function notFound($file){
include($file);
exit();
}
}
?>