Passed
Push — master ( 6923e5...88cee3 )
by Marwan
02:08
created

App::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 2.0006

Importance

Changes 7
Bugs 0 Features 0
Metric Value
cc 2
eloc 17
c 7
b 0
f 0
nc 2
nop 0
dl 0
loc 22
ccs 17
cts 18
cp 0.9444
crap 2.0006
rs 9.7
1
<?php
2
3
/**
4
 * @author Marwan Al-Soltany <[email protected]>
5
 * @copyright Marwan Al-Soltany 2021
6
 * For the full copyright and license information, please view
7
 * the LICENSE file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace MAKS\Velox;
13
14
use MAKS\Velox\Backend\Event;
15
use MAKS\Velox\Backend\Config;
16
use MAKS\Velox\Backend\Router;
17
use MAKS\Velox\Backend\Globals;
18
use MAKS\Velox\Backend\Session;
19
use MAKS\Velox\Backend\Database;
20
use MAKS\Velox\Backend\Auth;
21
use MAKS\Velox\Frontend\Data;
22
use MAKS\Velox\Frontend\View;
23
use MAKS\Velox\Frontend\HTML;
24
use MAKS\Velox\Frontend\Path;
25
use MAKS\Velox\Helper\Dumper;
26
use MAKS\Velox\Helper\Misc;
27
28
/**
29
 * A class that serves as a basic service-container for VELOX.
30
 * This class has most VELOX classes as public properties:
31
 * - `$auth`: Instance of the `Auth` class.
32
 * - `$event`: Instance of the `Event` class.
33
 * - `$config`: Instance of the `Config` class.
34
 * - `$router`: Instance of the `Router` class.
35
 * - `$globals`: Instance of the `Globals` class.
36
 * - `$session`: Instance of the `Session` class.
37
 * - `$database`: Instance of the `Database` class.
38
 * - `$data`: Instance of the `Data` class.
39
 * - `$view`: Instance of the `View` class.
40
 * - `$html`: Instance of the `HTML` class.
41
 * - `$path`: Instance of the `Path` class.
42
 * - `$dumper`: Instance of the `Dumper` class.
43
 * - `$misc`: Instance of the `Misc` class.
44
 *
45
 * Example:
46
 * ```
47
 * // create an instance
48
 * $app = new App();
49
 * // get an instance of the `Config` class via public property access notation
50
 * $app->config;
51
 * // or via calling a method with the same name
52
 * $app->config()->get('global');
53
 * ```
54
 *
55
 * @package Velox
56
 * @since 1.0.0
57
 * @api
58
 *
59
 * @method static void handleException(\Throwable $expression) This method is available only at shutdown.
60
 * @method static void handleError(int $code, string $message, string $file, int $line) This method is available only at shutdown.
61
 */
62
class App
63
{
64
    /**
65
     * This event will be dispatched on app termination. Note that this event can be dispatched multiple times in app life-cycle.
66
     * This event will not be passed any arguments.
67
     *
68
     * @var string
69
     */
70
    public const ON_TERMINATE = 'app.on.terminate';
71
72
    /**
73
     * This event will be dispatched on app shutdown. Note that this event is dispatched only once in app life-cycle.
74
     * This event will not be passed any arguments.
75
     *
76
     * @var string
77
     */
78
    public const ON_SHUTDOWN = 'app.on.shutdown';
79
80
81
    /**
82
     * The class singleton instance.
83
     */
84
    private static self $instance;
85
86
87
    public Event $event;
88
89
    public Config $config;
90
91
    public Router $router;
92
93
    public Globals $globals;
94
95
    public Session $session;
96
97
    public Database $database;
98
99
    public Auth $auth;
100
101
    public Data $data;
102
103
    public View $view;
104
105
    public HTML $html;
106
107
    public Path $path;
108
109
    public Dumper $dumper;
110
111
    public Misc $misc;
112
113
    protected array $methods;
114
115
    protected static array $staticMethods;
116
117
118
    /**
119
     * Class constructor.
120
     */
121 11
    public function __construct()
122
    {
123 11
        if (empty(static::$instance)) {
0 ignored issues
show
Bug introduced by
Since $instance is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $instance to at least protected.
Loading history...
124
            static::$instance = $this;
125
        }
126
127 11
        $this->event    = new Event();
128 11
        $this->config   = new Config();
129 11
        $this->router   = new Router();
130 11
        $this->globals  = new Globals();
131 11
        $this->session  = new Session();
132 11
        $this->database = Database::instance();
133 11
        $this->auth     = Auth::instance();
134 11
        $this->data     = new Data();
135 11
        $this->view     = new View();
136 11
        $this->html     = new HTML();
137 11
        $this->path     = new Path();
138 11
        $this->dumper   = new Dumper();
139 11
        $this->misc     = new Misc();
140
141 11
        $this->methods  = [];
142 11
        static::$staticMethods = [];
143 11
    }
144
145 2
    public function __get(string $property)
146
    {
147 2
        $class = static::class;
148
149 2
        throw new \Exception("Call to undefined property {$class}::${$property}");
150
    }
151
152 3
    public function __call(string $method, array $arguments)
153
    {
154 3
        $class = static::class;
155
156
        try {
157 3
            return isset($this->methods[$method]) ? $this->methods[$method](...$arguments) : $this->{$method};
158 1
        } catch (\Exception $error) {
159 1
            throw new \Exception(
160 1
                "Call to undefined method {$class}::{$method}()",
161 1
                (int)$error->getCode(),
162
                $error
163
            );
164
        }
165
    }
166
167 2
    public static function __callStatic(string $method, array $arguments)
168
    {
169 2
        $class = static::class;
170
171 2
        if (!isset(static::$staticMethods[$method])) {
172 1
            throw new \Exception("Call to undefined static method {$class}::{$method}()");
173
        }
174
175 1
        return static::$staticMethods[$method](...$arguments);
176
    }
177
178
179
    /**
180
     * Returns the singleton instance of the `App` class.
181
     *
182
     * NOTE: This method returns only the first instance of the class
183
     * which is normally the one that was created during application bootstrap.
184
     *
185
     * @return static
186
     *
187
     * @since 1.4.0
188
     */
189 3
    final public static function instance(): self
190
    {
191 3
        if (empty(static::$instance)) {
0 ignored issues
show
Bug introduced by
Since $instance is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $instance to at least protected.
Loading history...
192
            static::$instance = new static();
193
        }
194
195 3
        return static::$instance;
196
    }
197
198
    /**
199
     * Extends the class using the passed callback.
200
     *
201
     * @param string $name Method name.
202
     * @param callable $callback The callback to use as method body.
203
     *
204
     * @return callable The created bound closure.
205
     */
206 1
    public function extend(string $name, callable $callback): callable
207
    {
208 1
        $method = \Closure::fromCallable($callback);
209 1
        $method = \Closure::bind($method, $this, $this);
210
211 1
        return $this->methods[$name] = $method;
212
    }
213
214
    /**
215
     * Extends the class using the passed callback.
216
     *
217
     * @param string $name Method name.
218
     * @param callable $callback The callback to use as method body.
219
     *
220
     * @return callable The created closure.
221
     */
222 1
    public static function extendStatic(string $name, callable $callback): callable
223
    {
224 1
        $method = \Closure::fromCallable($callback);
225 1
        $method = \Closure::bind($method, null, static::class);
226
227 1
        return static::$staticMethods[$name] = $method;
228
    }
229
230
    /**
231
     * Logs a message to a file and generates it if it does not exist.
232
     *
233
     * @param string $message The message wished to be logged.
234
     * @param array|null $context An associative array of values where array key = {key} in the message (context).
235
     * @param string|null $filename [optional] The name wished to be given to the file. If not provided `{global.logging.defaultFilename}` will be used instead.
236
     * @param string|null $directory [optional] The directory where the log file should be written. If not provided `{global.logging.defaultDirectory}` will be used instead.
237
     *
238
     * @return bool True on success (if the message was written).
239
     */
240 26
    public static function log(string $message, ?array $context = [], ?string $filename = null, ?string $directory = null): bool
241
    {
242 26
        if (!Config::get('global.logging.enabled', true)) {
243 1
            return true;
244
        }
245
246 26
        $hasPassed = false;
247
248 26
        if (!$filename) {
249 1
            $filename = Config::get('global.logging.defaultFilename', sprintf('autogenerated-%s', date('Ymd')));
250
        }
251
252 26
        if (!$directory) {
253 26
            $directory = Config::get('global.logging.defaultDirectory', BASE_PATH);
254
        }
255
256 26
        $file = Path::normalize($directory, $filename, '.log');
257
258 26
        if (!file_exists($directory)) {
259 1
            mkdir($directory, 0744, true);
260
        }
261
262
        // create log file if it does not exist
263 26
        if (!is_file($file) && is_writable($directory)) {
264 2
            $signature = 'Created by ' . __METHOD__ . date('() \o\\n l jS \of F Y h:i:s A (Ymdhis)') . PHP_EOL . PHP_EOL;
265 2
            file_put_contents($file, $signature, 0);
266 2
            chmod($file, 0775);
267
        }
268
269
        // write in the log file
270 26
        if (is_writable($file)) {
271 26
            clearstatcache(true, $file);
272
            // empty the file if it exceeds the configured file size
273 26
            $maxFileSize = Config::get('global.logging.maxFileSize', 6.4e+7);
274 26
            if (filesize($file) > $maxFileSize) {
275 1
                $stream = fopen($file, 'r');
276 1
                if (is_resource($stream)) {
277 1
                    $signature = fgets($stream) . 'For exceeding the configured {global.logging.maxFileSize}, it was overwritten on ' . date('l jS \of F Y h:i:s A (Ymdhis)') . PHP_EOL . PHP_EOL;
278 1
                    fclose($stream);
279 1
                    file_put_contents($file, $signature, 0);
280 1
                    chmod($file, 0775);
281
                }
282
            }
283
284 26
            $timestamp = (new \DateTime())->format(DATE_ISO8601);
285 26
            $message   = Misc::interpolate($message, $context ?? []);
286
287 26
            $log = "$timestamp\t$message\n";
288
289 26
            $stream = fopen($file, 'a+');
290 26
            if (is_resource($stream)) {
291 26
                fwrite($stream, $log);
292 26
                fclose($stream);
293 26
                $hasPassed = true;
294
            }
295
        }
296
297 26
        return $hasPassed;
298
    }
299
300
    /**
301
     * Aborts the current request and sends a response with the specified HTTP status code, title, and message.
302
     * An HTML page will be rendered with the specified title and message.
303
     * If a view file for the error page is set using `{global.errorPages.CODE}`,
304
     * it will be rendered instead of the normal page and passed the `$code`, `$title`, and `$message` variables.
305
     * The title for the most common HTTP status codes (`200`, `401`, `403`, `404`, `405`, `500`, `503`) is already configured.
306
     *
307
     * @param int $code The HTTP status code.
308
     * @param string|null $title [optional] The title of the HTML page.
309
     * @param string|null $message [optional] The message of the HTML page.
310
     *
311
     * @return void
312
     *
313
     * @since 1.2.5
314
     */
315 4
    public static function abort(int $code, ?string $title = null, ?string $message = null): void
316
    {
317
        $http = [
318 4
            200 => 'OK',
319
            401 => 'Unauthorized',
320
            403 => 'Forbidden',
321
            404 => 'Not Found',
322
            405 => 'Not Allowed',
323
            500 => 'Internal Server Error',
324
            503 => 'Service Unavailable',
325
        ];
326
327 4
        $title    = htmlspecialchars($title ?? $code . ' ' . $http[$code] ?? '', ENT_QUOTES, 'UTF-8');
328 4
        $message  = htmlspecialchars($message ?? '', ENT_QUOTES, 'UTF-8');
329
330
        try {
331 4
            $html = View::render(Config::get("global.errorPages.{$code}"), compact('code', 'title', 'message'));
0 ignored issues
show
Bug introduced by
It seems like MAKS\Velox\Backend\Confi...bal.errorPages.'.$code) can also be of type null; however, parameter $page of MAKS\Velox\Frontend\View::render() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

331
            $html = View::render(/** @scrutinizer ignore-type */ Config::get("global.errorPages.{$code}"), compact('code', 'title', 'message'));
Loading history...
332 1
        } catch (\Throwable $e) {
333 1
            $html = (new HTML(false))
334 1
                ->node('<!DOCTYPE html>')
335 1
                ->open('html', ['lang' => 'en'])
336 1
                    ->open('head')
337 1
                        ->title((string)$code)
338 1
                        ->link(null, [
339 1
                            'href' => 'https://cdn.jsdelivr.net/npm/bulma@latest/css/bulma.min.css',
340
                            'rel' => 'stylesheet'
341
                        ])
342 1
                    ->close()
343 1
                    ->open('body')
344 1
                        ->open('section', ['class' => 'section is-large has-text-centered'])
345 1
                            ->hr(null)
346 1
                            ->h1($title, ['class' => 'title is-1 is-spaced has-text-danger'])
347 1
                            ->condition(strlen($message))
348 1
                            ->h4($message, ['class' => 'subtitle'])
349 1
                            ->hr(null)
350 1
                            ->a('Reload', ['class' => 'button is-warning is-light', 'href' => 'javascript:location.reload();'])
351 1
                            ->entity('nbsp')
352 1
                            ->entity('nbsp')
353 1
                            ->a('Home', ['class' => 'button is-success is-light', 'href' => '/'])
354 1
                            ->hr(null)
355 1
                        ->close()
356 1
                    ->close()
357 1
                ->close()
358 1
            ->return();
359
        } finally {
360 4
            http_response_code($code);
361 4
            echo $html;
362
363 4
            static::terminate();
364
        }
365
    }
366
367
368
    /**
369
     * Terminates (exits) the PHP script.
370
     * This function is used instead of PHP `exit` to allow for testing `exit` without breaking the unit tests.
371
     *
372
     * @param int|string|null $status The exit status code/message.
373
     * @param bool $noShutdown Whether to not execute the shutdown function or not.
374
     *
375
     * @return void This function never returns. It will terminate the script.
376
     * @throws \Exception If `EXIT_EXCEPTION` is defined and truthy.
377
     *
378
     * @since 1.2.5
379
     */
380 5
    public static function terminate($status = null, bool $noShutdown = true): void
381
    {
382 5
        Event::dispatch(self::ON_TERMINATE);
383
384 5
        if (defined('EXIT_EXCEPTION') && EXIT_EXCEPTION) {
385 5
            throw new \Exception(empty($status) ? 'Exit' : 'Exit: ' . $status);
386
        }
387
388
        // @codeCoverageIgnoreStart
389
        if ($noShutdown) {
390
            // app shutdown function checks for this variable
391
            // to determine if it should exit, see bootstrap/loader.php
392
            Misc::setArrayValueByKey($GLOBALS, '_VELOX.TERMINATE', true);
393
        }
394
395
        exit($status);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
396
        // @codeCoverageIgnoreEnd
397
    }
398
399
    /**
400
     * Shuts the app down by terminating it and executing shutdown function(s).
401
     * The triggered shutdown functions can be normal shutdown functions registered,
402
     * using `register_shutdown_function()` or the `self::ON_SHUTDOWN` event.
403
     *
404
     * @return void
405
     *
406
     * @internal This method is to be used by the framework and not the user.
407
     * @since 1.4.2
408
     *
409
     * @codeCoverageIgnore
410
     */
411
    public static function shutdown(): void
412
    {
413
        Event::dispatch(self::ON_SHUTDOWN);
414
415
        Misc::setArrayValueByKey($GLOBALS, '_VELOX.SHUTDOWN', false);
416
417
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
418
    }
419
}
420