-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRouterUtils.php
72 lines (65 loc) · 1.96 KB
/
RouterUtils.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
<?php
/**
* Class RouterUtils
* Tools to facilitate the use of the Router
*/
class RouterUtils{
/**
* @param string $url
* The input url, ex: /api/v1/articles/2/paragraphs/1
* @return string
* url used for routing the API, ex: /articles/2/paragraphs/1
*/
static function extractRealApiRoute(string $url): string {
$temp = explode('/', $url);
array_shift($temp);
array_shift($temp);
array_shift($temp);
return '/' . implode('/', $temp);
}
const URL_PARAMS = 'URL_PARAMS';
const BODY_DATA = "BODY_DATA";
/**
* Get the body data of the incoming request
* @return array
* Associative array corresponding to the json in the body of the request
*/
static function getBodyData(): array {
$data = json_decode(file_get_contents('php://input'), true);
return !is_null($data)? $data:array();
}
/**
* Test to check if the router found a valid route
* @param array $result
* The array return by the getMatch() method
* [callable, $params]
* @return bool
*/
static function isRouteFound(array $result): bool {
if (empty($result)) {
return false;
} else {
return true;
}
}
/**
* Execute the callback corresponding to the route
* @param array $result
* [callable, $params]
* @param array $data
* Associative array containing parameters (URL_PARAMS) of the url and json of the body (BODY_DATA)
*/
static function executeRoute(array $result, array $data) {
$args = array(self::URL_PARAMS => $result[1], self::BODY_DATA => $data);
call_user_func($result[0], $args);
}
/**
* Send the response to the client
* @param string $json
* THe message to send
*/
static function response(string $json){
header('Content-Type: application/json');
echo $json;
}
}