blob: 377c00baa80af956c1c23711337cd79be92ba65f (
plain)
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
|
<?php
namespace Elements;
use Elements\Controller\Card;
use Elements\Controller\Home;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class Router
{
private $routes = [
'GET' => [
'/' => [Home::class, 'index'],
],
'POST' => [
'/card/add' => [Card::class, 'add'],
],
];
/**
* Router constructor.
*/
public function __construct()
{
$request = Request::createFromGlobals();
$response = new Response();
$method = $request->getMethod();
$path = $request->getPathInfo();
// if the route is defined
if (isset($this->routes[$method][$path])) {
try {
// run controller function
$content = call_user_func($this->routes[$method][$path], $request);
// set response to new response
if ($content instanceof Response) {
$response = $content;
}
// set content directly otherwise
else {
$response->setContent($content);
}
}
// catch any errors
catch (AppException $exception) {
$response->setStatusCode($exception->getCode());
$response->setContent($exception->getMessage());
} catch (\Exception $exception) {
$response->setStatusCode(Response::HTTP_BAD_REQUEST);
$response->setContent($exception->getMessage());
}
}
// route is not defined
else {
$response->setStatusCode(Response::HTTP_NOT_FOUND);
$response->setContent('Not Found');
}
$response->send();
}
}
|