summaryrefslogtreecommitdiff
path: root/lib/router.php
blob: 979968d4868d2a7b0b577de430a2843e1bb6b7f6 (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
<?php

class Router
{
    private $controller = '';
    private $action = '';

    public function __construct($controller = '', $action = '')
    {
        $this->controller = empty($_GET['controller']) ? $controller : $_GET['controller'];
        $this->action = empty($_GET['action']) ? $controller : $_GET['action'];
    }

    public function sanitize($value, $default_value)
    {
        return ! ctype_alpha($value) || empty($value) ? $default_value : strtolower($value);
    }

    public function loadController($filename, $class, $method)
    {
        if (file_exists($filename)) {

            require $filename;

            if (! method_exists($class, $method)) return false;

            $instance = new $class;
            $instance->beforeAction($this->controller, $this->action);
            $instance->$method();

            return true;
        }

        return false;
    }

    public function execute()
    {
        $this->controller = $this->sanitize($this->controller, 'app');
        $this->action = $this->sanitize($this->action, 'index');

        if (! $this->loadController('controllers/'.$this->controller.'.php', '\Controller\\'.$this->controller, $this->action)) {
            die('Page not found!');
        }
    }
}