Completed
Push — master ( d8c11b...7120c2 )
by Mikołaj
17:24
created

App::loadRoutes()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 29
rs 8.8571
cc 3
eloc 17
nc 3
nop 0
1
<?php
2
3
namespace Egzaminer;
4
5
use AltoRouter;
6
use Exception;
7
use PDO;
8
use PDOException;
9
use Tamtamchik\SimpleFlash\Flash;
10
use Whoops\Handler\PrettyPageHandler;
11
use Whoops\Run as Whoops;
12
13
class App
14
{
15
    const VERSION = '0.12.0';
16
17
    /**
18
     * @var string
19
     */
20
    private $url;
21
22
    /**
23
     * @var AltoRouter
24
     */
25
    private $router;
26
27
    /**
28
     * @var array
29
     */
30
    private $config;
31
32
    /**
33
     * @var array
34
     */
35
    private $container;
36
37
    /**
38
     * Constructor.
39
     *
40
     * @param string $url
41
     */
42
    public function __construct($url)
0 ignored issues
show
Coding Style introduced by
__construct uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
__construct uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
__construct uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
__construct uses the super-global variable $_COOKIE which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
__construct uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
__construct uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
43
    {
44
        try {
45
            $configPath = $this->getRootDir().'/config/site.php';
46
            if (!file_exists($configPath)) {
47
                http_response_code(500);
48
                throw new Exception('Config file site.php does not exist');
49
            }
50
            $this->config = include $configPath;
51
52
            if ($this->config['debug']) {
53
                $whoops = new Whoops();
54
                $whoops->pushHandler(new PrettyPageHandler());
0 ignored issues
show
Documentation introduced by
new \Whoops\Handler\PrettyPageHandler() is of type object<Whoops\Handler\PrettyPageHandler>, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
55
                $whoops->register();
56
            }
57
58
            $this->container = [
59
                'config'  => $this->config,
60
                'dbh'     => $this->dbConnect(include $this->getRootDir().'/config/db.php'),
61
                'dir'     => $this->getDir(),
62
                'flash'   => new Flash(),
63
                'request' => [
64
                    'get'     => $_GET,
65
                    'post'    => $_POST,
66
                    'session' => &$_SESSION,
67
                    'cookie'  => $_COOKIE,
68
                    'files'   => $_FILES,
69
                    'server'  => $_SERVER,
70
                ],
71
                'rootDir' => $this->getRootDir(),
72
                'version' => self::VERSION,
73
            ];
74
75
            $configPath = $this->getRootDir().'/config/users.php';
76
            if (!file_exists($configPath)) {
77
                http_response_code(500);
78
                throw new Exception('Config file users.php does not exist');
79
            }
80
81
            $this->container['auth'] = new Auth(include $configPath, $this->container['request']);
82
        } catch (Exception $e) {
83
            http_response_code(500);
84
            echo $e->getMessage();
85
            $this->terminate();
86
        }
87
88
        $this->router = new AltoRouter();
89
        $this->setUrl($url);
90
    }
91
92
    /**
93
     * Run app.
94
     */
95
    public function invoke()
96
    {
97
        $this->loadRoutes();
98
99
        $match = $this->router->match($this->url);
100
101
        try {
102
            // call closure or throw 404 status
103
            if ($match && is_callable($match['target'])) {
104
                call_user_func_array([
105
                    new $match['target'][0]($this->container), $match['target'][1],
106
                ], $match['params']);
107
            } else {
108
                throw new Exception('Page not exist! No route match');
109
            }
110
        } catch (Exception $e) {
111
            if ($this->config['debug']) {
112
                throw new DebugException($e->getMessage());
113
            } else {
114
                (new Error($this->container))->showAction(404);
115
            }
116
            $this->terminate();
117
        }
118
    }
119
120
    /**
121
     * Load routes.
122
     *
123
     * @return void
124
     */
125
    public function loadRoutes()
126
    {
127
        $routesArray = include __DIR__.'/routes.php';
128
129
        foreach ($routesArray as $key => $route) {
130
            if (2 === count($route)) {
131
                $this->router->map(
132
                    $route[0][0],
133
                    $route[0][1],
134
                    [
135
                        'Egzaminer\Controller\\'.$route[0][2][0],
136
                        $route[0][2][1]
137
                    ],
138
                    $key.'/'.$route[0][0]
139
                );
140
                $route = $route[1];
141
            }
142
143
            $this->router->map(
144
                $route[0],
145
                $route[1],
146
                [
147
                    'Egzaminer\Controller\\'.$route[2][0],
148
                    $route[2][1]
149
                ],
150
                $key.'/'.$route[0]
151
            );
152
        }
153
    }
154
155
    private function dbConnect(array $config)
156
    {
157
        try {
158
            $dsn = 'mysql'
159
            .':dbname='.$config['name']
160
            .';host='.$config['host']
161
            .';charset=utf8';
162
163
            $user = $config['user'];
164
            $password = $config['pass'];
165
166
            $dbh = new PDO($dsn, $user, $password);
167
168
            if ($this->config['debug']) {
169
                $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
170
            }
171
172
            return $dbh;
173
        } catch (PDOException $e) {
174
            http_response_code(500);
175
176
            if ($this->config['debug']) {
177
                throw new DebugException($e->getMessage());
178
            } else {
179
                echo 'Error 500';
180
            }
181
            $this->terminate();
182
        }
183
    }
184
185
    public function terminate($code = 1)
186
    {
187
        exit($code);
0 ignored issues
show
Coding Style Compatibility introduced by
The method terminate() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
188
    }
189
190
    /**
191
     * Set request url.
192
     *
193
     * @param string $request
194
     */
195
    public function setUrl($request)
196
    {
197
        $this->url = substr($request, strlen($this->getDir()));
198
    }
199
200
    /**
201
     * Get app root dir.
202
     *
203
     * @return string
204
     */
205
    public function getRootDir()
206
    {
207
        return dirname(__DIR__);
208
    }
209
210
    /**
211
     * Get app dir.
212
     *
213
     * @return string
214
     */
215
    public function getDir()
0 ignored issues
show
Coding Style introduced by
getDir uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
216
    {
217
        if (dirname($_SERVER['SCRIPT_NAME']) == '/') {
218
            return '';
219
        }
220
221
        return dirname($_SERVER['SCRIPT_NAME']);
222
    }
223
}
224