Passed
Pull Request — master (#1)
by Yohann
06:03
created

Router::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
rs 10
1
<?php
2
3
namespace mvc\core;
4
5
class Router
6
{
7
8
    public Request $request;
9
    public Response $response;
10
11
    protected array $routes = [];
12
13
    public function __construct(Request $request, Response $response)
14
    {
15
        $this->request = $request;
16
        $this->response = $response;
17
    }
18
19
    public function get($uri, $controller, $method)
20
    {
21
        $this->routes['get'][$uri] = [$controller, $method];
22
    }
23
24
    public function post($uri, $controller, $method)
25
    {
26
        $this->routes['post'][$uri] = [$controller, $method];
27
    }
28
29
    public function resolve()
30
    {
31
        $path = $this->request->getPath();
32
        $method = $this->request->getMethod();
33
34
        $callback = $this->routes[$method][$path] ?? false;
35
36
        if ($callback === false) {
37
            $this->response->setStatusCode(404);
38
            $callback = $this->routes['get']['404'] ?? '404 Not Found';
39
        }
40
41
        if (is_string($callback)) {
42
            return $callback;
43
        }
44
45
        $controllerName = ucfirst(array_shift($callback)) . 'Controller';
46
        include ROOT_DIR . "/app/controllers/$controllerName.php";
47
        $controller = new $controllerName;
48
49
        $method = array_shift($callback);
50
51
        return $controller->$method();
52
    }
53
}
54