Passed
Push — master ( 48e2e4...58f05f )
by Marwan
08:52
created

App   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 349
Duplicated Lines 0 %

Test Coverage

Coverage 96.55%

Importance

Changes 21
Bugs 0 Features 0
Metric Value
c 21
b 0
f 0
dl 0
loc 349
ccs 112
cts 116
cp 0.9655
rs 10
eloc 141
wmc 30

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 22 2
A terminate() 0 16 5
A instance() 0 7 2
A shutdown() 0 7 1
B log() 0 58 11
A extend() 0 6 1
A abort() 0 49 2
A __callStatic() 0 9 2
A __call() 0 11 3
A extendStatic() 0 6 1
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
    protected 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 10
    public function __construct()
122
    {
123 10
        if (empty(static::$instance)) {
124
            static::$instance = $this;
125
        }
126
127 10
        $this->event    = new Event();
128 10
        $this->config   = new Config();
129 10
        $this->router   = new Router();
130 10
        $this->globals  = new Globals();
131 10
        $this->session  = new Session();
132 10
        $this->database = Database::instance();
133 10
        $this->auth     = Auth::instance();
134 10
        $this->data     = new Data();
135 10
        $this->view     = new View();
136 10
        $this->html     = new HTML();
137 10
        $this->path     = new Path();
138 10
        $this->dumper   = new Dumper();
139 10
        $this->misc     = new Misc();
140
141 10
        $this->methods  = [];
142 10
        static::$staticMethods = [];
143 10
    }
144
145 3
    public function __call(string $method, array $arguments)
146
    {
147 3
        $class = static::class;
148
149
        try {
150 3
            return isset($this->methods[$method]) ? $this->methods[$method](...$arguments) : $this->{$method};
151 1
        } catch (\Exception $error) {
152 1
            throw new \Exception(
153 1
                "Call to undefined method {$class}::{$method}()",
154 1
                (int)$error->getCode(),
155
                $error
156
            );
157
        }
158
    }
159
160 2
    public static function __callStatic(string $method, array $arguments)
161
    {
162 2
        $class = static::class;
163
164 2
        if (!isset(static::$staticMethods[$method])) {
165 1
            throw new \Exception("Call to undefined static method {$class}::{$method}()");
166
        }
167
168 1
        return static::$staticMethods[$method](...$arguments);
169
    }
170
171
172
    /**
173
     * Returns the singleton instance of the `App` class.
174
     *
175
     * NOTE: This method returns only the first instance of the class
176
     * which is normally the one that was created during application bootstrap.
177
     *
178
     * @return static
179
     *
180
     * @since 1.4.0
181
     */
182 3
    final public static function instance(): self
183
    {
184 3
        if (empty(static::$instance)) {
185
            static::$instance = new static();
186
        }
187
188 3
        return static::$instance;
189
    }
190
191
    /**
192
     * Extends the class using the passed callback.
193
     *
194
     * @param string $name Method name.
195
     * @param callable $callback The callback to use as method body.
196
     *
197
     * @return callable The created bound closure.
198
     */
199 1
    public function extend(string $name, callable $callback): callable
200
    {
201 1
        $method = \Closure::fromCallable($callback);
202 1
        $method = \Closure::bind($method, $this, $this);
203
204 1
        return $this->methods[$name] = $method;
205
    }
206
207
    /**
208
     * Extends the class using the passed callback.
209
     *
210
     * @param string $name Method name.
211
     * @param callable $callback The callback to use as method body.
212
     *
213
     * @return callable The created closure.
214
     */
215 1
    public static function extendStatic(string $name, callable $callback): callable
216
    {
217 1
        $method = \Closure::fromCallable($callback);
218 1
        $method = \Closure::bind($method, null, static::class);
219
220 1
        return static::$staticMethods[$name] = $method;
221
    }
222
223
    /**
224
     * Logs a message to a file and generates it if it does not exist.
225
     *
226
     * @param string $message The message wished to be logged.
227
     * @param array|null $context An associative array of values where array key = {key} in the message (context).
228
     * @param string|null $filename [optional] The name wished to be given to the file. If not provided `{global.logging.defaultFilename}` will be used instead.
229
     * @param string|null $directory [optional] The directory where the log file should be written. If not provided `{global.logging.defaultDirectory}` will be used instead.
230
     *
231
     * @return bool True on success (if the message was written).
232
     */
233 27
    public static function log(string $message, ?array $context = [], ?string $filename = null, ?string $directory = null): bool
234
    {
235 27
        if (!Config::get('global.logging.enabled', true)) {
236 1
            return true;
237
        }
238
239 27
        $hasPassed = false;
240
241 27
        if (!$filename) {
242 1
            $filename = Config::get('global.logging.defaultFilename', sprintf('autogenerated-%s', date('Ymd')));
243
        }
244
245 27
        if (!$directory) {
246 27
            $directory = Config::get('global.logging.defaultDirectory', BASE_PATH);
247
        }
248
249 27
        $file = Path::normalize($directory, $filename, '.log');
250
251 27
        if (!file_exists($directory)) {
252 1
            mkdir($directory, 0744, true);
253
        }
254
255
        // create log file if it does not exist
256 27
        if (!is_file($file) && is_writable($directory)) {
257 2
            $signature = 'Created by ' . __METHOD__ . date('() \o\\n l jS \of F Y h:i:s A (Ymdhis)') . PHP_EOL . PHP_EOL;
258 2
            file_put_contents($file, $signature, 0);
259 2
            chmod($file, 0775);
260
        }
261
262
        // write in the log file
263 27
        if (is_writable($file)) {
264 27
            clearstatcache(true, $file);
265
            // empty the file if it exceeds the configured file size
266 27
            $maxFileSize = Config::get('global.logging.maxFileSize', 6.4e+7);
267 27
            if (filesize($file) > $maxFileSize) {
268 1
                $stream = fopen($file, 'r');
269 1
                if (is_resource($stream)) {
270 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;
271 1
                    fclose($stream);
272 1
                    file_put_contents($file, $signature, 0);
273 1
                    chmod($file, 0775);
274
                }
275
            }
276
277 27
            $timestamp = (new \DateTime())->format(DATE_ISO8601);
278 27
            $message   = Misc::interpolate($message, $context ?? []);
279
280 27
            $log = "$timestamp\t$message\n";
281
282 27
            $stream = fopen($file, 'a+');
283 27
            if (is_resource($stream)) {
284 27
                fwrite($stream, $log);
285 27
                fclose($stream);
286 27
                $hasPassed = true;
287
            }
288
        }
289
290 27
        return $hasPassed;
291
    }
292
293
    /**
294
     * Aborts the current request and sends a response with the specified HTTP status code, title, and message.
295
     * An HTML page will be rendered with the specified title and message.
296
     * If a view file for the error page is set using `{global.errorPages.CODE}`,
297
     * it will be rendered instead of the normal page and passed the `$code`, `$title`, and `$message` variables.
298
     * The title for the most common HTTP status codes (`200`, `401`, `403`, `404`, `405`, `500`, `503`) is already configured.
299
     *
300
     * @param int $code The HTTP status code.
301
     * @param string|null $title [optional] The title of the HTML page.
302
     * @param string|null $message [optional] The message of the HTML page.
303
     *
304
     * @return void
305
     *
306
     * @since 1.2.5
307
     */
308 4
    public static function abort(int $code, ?string $title = null, ?string $message = null): void
309
    {
310
        $http = [
311 4
            200 => 'OK',
312
            401 => 'Unauthorized',
313
            403 => 'Forbidden',
314
            404 => 'Not Found',
315
            405 => 'Not Allowed',
316
            500 => 'Internal Server Error',
317
            503 => 'Service Unavailable',
318
        ];
319
320 4
        $title    = htmlspecialchars($title ?? $code . ' ' . $http[$code] ?? '', ENT_QUOTES, 'UTF-8');
321 4
        $message  = htmlspecialchars($message ?? '', ENT_QUOTES, 'UTF-8');
322
323
        try {
324 4
            $html = View::render((string)Config::get("global.errorPages.{$code}"), compact('code', 'title', 'message'));
325 1
        } catch (\Throwable $e) {
326 1
            $html = (new HTML(false))
327 1
                ->node('<!DOCTYPE html>')
328 1
                ->open('html', ['lang' => 'en'])
329 1
                    ->open('head')
330 1
                        ->title((string)$code)
331 1
                        ->link(null, [
332 1
                            'href' => 'https://cdn.jsdelivr.net/npm/bulma@latest/css/bulma.min.css',
333
                            'rel' => 'stylesheet'
334
                        ])
335 1
                    ->close()
336 1
                    ->open('body')
337 1
                        ->open('section', ['class' => 'section is-large has-text-centered'])
338 1
                            ->hr(null)
339 1
                            ->h1($title, ['class' => 'title is-1 is-spaced has-text-danger'])
340 1
                            ->condition(strlen($message))
341 1
                            ->h4($message, ['class' => 'subtitle'])
342 1
                            ->hr(null)
343 1
                            ->a('Reload', ['class' => 'button is-warning is-light', 'href' => 'javascript:location.reload();'])
344 1
                            ->entity('nbsp')
345 1
                            ->entity('nbsp')
346 1
                            ->a('Home', ['class' => 'button is-success is-light', 'href' => '/'])
347 1
                            ->hr(null)
348 1
                        ->close()
349 1
                    ->close()
350 1
                ->close()
351 1
            ->return();
352
        } finally {
353 4
            http_response_code($code);
354 4
            echo $html;
355
356 4
            static::terminate();
357
        }
358
    }
359
360
361
    /**
362
     * Terminates (exits) the PHP script.
363
     * This function is used instead of PHP `exit` to allow for testing `exit` without breaking the unit tests.
364
     *
365
     * @param int|string|null $status The exit status code/message.
366
     * @param bool $noShutdown Whether to not execute the shutdown function or not.
367
     *
368
     * @return void This function never returns. It will terminate the script.
369
     * @throws \Exception If `EXIT_EXCEPTION` is defined and truthy.
370
     *
371
     * @since 1.2.5
372
     */
373 5
    public static function terminate($status = null, bool $noShutdown = true): void
374
    {
375 5
        Event::dispatch(self::ON_TERMINATE);
376
377 5
        if (defined('EXIT_EXCEPTION') && EXIT_EXCEPTION) {
378 5
            throw new \Exception(empty($status) ? 'Exit' : 'Exit: ' . $status);
379
        }
380
381
        // @codeCoverageIgnoreStart
382
        if ($noShutdown) {
383
            // app shutdown function checks for this variable
384
            // to determine if it should exit, see bootstrap/loader.php
385
            Misc::setArrayValueByKey($GLOBALS, '_VELOX.TERMINATE', true);
386
        }
387
388
        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...
389
        // @codeCoverageIgnoreEnd
390
    }
391
392
    /**
393
     * Shuts the app down by terminating it and executing shutdown function(s).
394
     * The triggered shutdown functions can be normal shutdown functions registered,
395
     * using `register_shutdown_function()` or the `self::ON_SHUTDOWN` event.
396
     *
397
     * @return void
398
     *
399
     * @internal This method is to be used by the framework and not the user.
400
     * @since 1.4.2
401
     *
402
     * @codeCoverageIgnore
403
     */
404
    public static function shutdown(): void
405
    {
406
        Event::dispatch(self::ON_SHUTDOWN);
407
408
        Misc::setArrayValueByKey($GLOBALS, '_VELOX.SHUTDOWN', false);
409
410
        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...
411
    }
412
}
413