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

Router   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 21
c 3
b 0
f 0
dl 0
loc 47
rs 10
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A resolve() 0 23 3
A get() 0 3 1
A post() 0 3 1
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