Passed
Push — master ( 766bf6...808da0 )
by Marwan
07:32
created

App::__call()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
c 5
b 0
f 0
nc 4
nop 2
dl 0
loc 12
ccs 7
cts 7
cp 1
crap 3
rs 9.9666
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\Exception;
15
use MAKS\Velox\Backend\Event;
16
use MAKS\Velox\Backend\Config;
17
use MAKS\Velox\Backend\Router;
18
use MAKS\Velox\Backend\Globals;
19
use MAKS\Velox\Backend\Session;
20
use MAKS\Velox\Backend\Database;
21
use MAKS\Velox\Backend\Auth;
22
use MAKS\Velox\Frontend\Data;
23
use MAKS\Velox\Frontend\View;
24
use MAKS\Velox\Frontend\HTML;
25
use MAKS\Velox\Frontend\Path;
26
use MAKS\Velox\Helper\Dumper;
27
use MAKS\Velox\Helper\Misc;
28
29
/**
30
 * A class that serves as a basic service-container for VELOX.
31
 * This class has most VELOX classes as public properties:
32
 * - `$auth`: Instance of the `Auth` class.
33
 * - `$event`: Instance of the `Event` class.
34
 * - `$config`: Instance of the `Config` class.
35
 * - `$router`: Instance of the `Router` class.
36
 * - `$globals`: Instance of the `Globals` class.
37
 * - `$session`: Instance of the `Session` class.
38
 * - `$database`: Instance of the `Database` class.
39
 * - `$data`: Instance of the `Data` class.
40
 * - `$view`: Instance of the `View` class.
41
 * - `$html`: Instance of the `HTML` class.
42
 * - `$path`: Instance of the `Path` class.
43
 * - `$dumper`: Instance of the `Dumper` class.
44
 * - `$misc`: Instance of the `Misc` class.
45
 *
46
 * Example:
47
 * ```
48
 * // create an instance
49
 * $app = new App();
50
 * // get an instance of the `Config` class via public property access notation
51
 * $app->config;
52
 * // or via calling a method with the same name
53
 * $app->config()->get('global');
54
 * ```
55
 *
56
 * @package Velox
57
 * @since 1.0.0
58
 * @api
59
 *
60
 * @method static void handleException(\Throwable $expression) This method is available only at shutdown.
61
 * @method static void handleError(int $code, string $message, string $file, int $line) This method is available only at shutdown.
62
 */
63
class App
64
{
65
    /**
66
     * This event will be dispatched on app termination. Note that this event can be dispatched multiple times in app life-cycle.
67
     * This event will not be passed any arguments.
68
     *
69
     * @var string
70
     */
71
    public const ON_TERMINATE = 'app.on.terminate';
72
73
    /**
74
     * This event will be dispatched on app shutdown. Note that this event is dispatched only once in app life-cycle.
75
     * This event will not be passed any arguments.
76
     *
77
     * @var string
78
     */
79
    public const ON_SHUTDOWN = 'app.on.shutdown';
80
81
82
    /**
83
     * The class singleton instance.
84
     */
85
    protected static self $instance;
86
87
88
    public Event $event;
89
90
    public Config $config;
91
92
    public Router $router;
93
94
    public Globals $globals;
95
96
    public Session $session;
97
98
    public Database $database;
99
100
    public Auth $auth;
101
102
    public Data $data;
103
104
    public View $view;
105
106
    public HTML $html;
107
108
    public Path $path;
109
110
    public Dumper $dumper;
111
112
    public Misc $misc;
113
114
    protected array $methods;
115
116
    protected static array $staticMethods;
117
118
119
    /**
120
     * Class constructor.
121
     */
122 10
    public function __construct()
123
    {
124 10
        if (empty(static::$instance)) {
125
            static::$instance = $this;
126
        }
127
128 10
        $this->event    = new Event();
129 10
        $this->config   = new Config();
130 10
        $this->router   = new Router();
131 10
        $this->globals  = new Globals();
132 10
        $this->session  = new Session();
133 10
        $this->database = Database::instance();
134 10
        $this->auth     = Auth::instance();
135 10
        $this->data     = new Data();
136 10
        $this->view     = new View();
137 10
        $this->html     = new HTML();
138 10
        $this->path     = new Path();
139 10
        $this->dumper   = new Dumper();
140 10
        $this->misc     = new Misc();
141
142 10
        $this->methods  = [];
143 10
        static::$staticMethods = [];
144
    }
145
146 3
    public function __call(string $method, array $arguments)
147
    {
148 3
        $class = static::class;
149
150
        try {
151 3
            return isset($this->methods[$method]) ? $this->methods[$method](...$arguments) : $this->{$method};
152 1
        } catch (\Exception $error) {
153 1
            Exception::throw(
154
                'UndefinedMethodException:BadMethodCallException',
155 1
                "Call to undefined method {$class}::{$method}()",
156 1
                $error->getCode(),
157
                $error,
158
            );
159
        }
160
    }
161
162 2
    public static function __callStatic(string $method, array $arguments)
163
    {
164 2
        $class = static::class;
165
166 2
        if (!isset(static::$staticMethods[$method])) {
167 1
            Exception::throw(
168
                'UndefinedStaticMethodException:BadMethodCallException',
169 1
                "Call to undefined static method {$class}::{$method}()"
170
            );
171
        }
172
173 1
        return static::$staticMethods[$method](...$arguments);
174
    }
175
176
177
    /**
178
     * Returns the singleton instance of the `App` class.
179
     *
180
     * NOTE: This method returns only the first instance of the class
181
     * which is normally the one that was created during application bootstrap.
182
     *
183
     * @return static
184
     *
185
     * @since 1.4.0
186
     */
187 3
    final public static function instance(): self
188
    {
189 3
        if (empty(static::$instance)) {
190
            static::$instance = new static();
191
        }
192
193 3
        return static::$instance;
194
    }
195
196
    /**
197
     * Extends the class using the passed callback.
198
     *
199
     * @param string $name Method name.
200
     * @param callable $callback The callback to use as method body.
201
     *
202
     * @return callable The created bound closure.
203
     */
204 1
    public function extend(string $name, callable $callback): callable
205
    {
206 1
        $method = \Closure::fromCallable($callback);
207 1
        $method = \Closure::bind($method, $this, $this);
208
209 1
        return $this->methods[$name] = $method;
210
    }
211
212
    /**
213
     * Extends the class using the passed callback.
214
     *
215
     * @param string $name Method name.
216
     * @param callable $callback The callback to use as method body.
217
     *
218
     * @return callable The created closure.
219
     */
220 1
    public static function extendStatic(string $name, callable $callback): callable
221
    {
222 1
        $method = \Closure::fromCallable($callback);
223 1
        $method = \Closure::bind($method, null, static::class);
224
225 1
        return static::$staticMethods[$name] = $method;
226
    }
227
228
    /**
229
     * Logs a message to a file and generates it if it does not exist.
230
     *
231
     * @param string $message The message wished to be logged.
232
     * @param array|null $context An associative array of values where array key = {key} in the message (context).
233
     * @param string|null $filename [optional] The name wished to be given to the file. If not provided `{global.logging.defaultFilename}` will be used instead.
234
     * @param string|null $directory [optional] The directory where the log file should be written. If not provided `{global.logging.defaultDirectory}` will be used instead.
235
     *
236
     * @return bool True on success (if the message was written).
237
     */
238 27
    public static function log(string $message, ?array $context = [], ?string $filename = null, ?string $directory = null): bool
239
    {
240 27
        if (!Config::get('global.logging.enabled', true)) {
241 1
            return true;
242
        }
243
244 27
        $hasPassed = false;
245
246 27
        if (!$filename) {
247 1
            $filename = Config::get('global.logging.defaultFilename', sprintf('autogenerated-%s', date('Ymd')));
248
        }
249
250 27
        if (!$directory) {
251 27
            $directory = Config::get('global.logging.defaultDirectory', BASE_PATH);
252
        }
253
254 27
        $file = Path::normalize($directory, $filename, '.log');
255
256 27
        if (!file_exists($directory)) {
257 1
            mkdir($directory, 0744, true);
258
        }
259
260
        // create log file if it does not exist
261 27
        if (!is_file($file) && is_writable($directory)) {
262 2
            $signature = 'Created by ' . __METHOD__ . date('() \o\\n l jS \of F Y h:i:s A (Ymdhis)') . PHP_EOL . PHP_EOL;
263 2
            file_put_contents($file, $signature, 0);
264 2
            chmod($file, 0775);
265
        }
266
267
        // write in the log file
268 27
        if (is_writable($file)) {
269 27
            clearstatcache(true, $file);
270
            // empty the file if it exceeds the configured file size
271 27
            $maxFileSize = Config::get('global.logging.maxFileSize', 6.4e+7);
272 27
            if (filesize($file) > $maxFileSize) {
273 1
                $stream = fopen($file, 'r');
274 1
                if (is_resource($stream)) {
275 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;
276 1
                    fclose($stream);
277 1
                    file_put_contents($file, $signature, 0);
278 1
                    chmod($file, 0775);
279
                }
280
            }
281
282 27
            $timestamp = (new \DateTime())->format(DATE_ISO8601);
283 27
            $message   = Misc::interpolate($message, $context ?? []);
284
285 27
            $log = "$timestamp\t$message\n";
286
287 27
            $stream = fopen($file, 'a+');
288 27
            if (is_resource($stream)) {
289 27
                fwrite($stream, $log);
290 27
                fclose($stream);
291 27
                $hasPassed = true;
292
            }
293
        }
294
295 27
        return $hasPassed;
296
    }
297
298
    /**
299
     * Aborts the current request and sends a response with the specified HTTP status code, title, and message.
300
     * An HTML page will be rendered with the specified title and message.
301
     * If a view file for the error page is set using `{global.errorPages.CODE}`,
302
     * it will be rendered instead of the normal page and passed the `$code`, `$title`, and `$message` variables.
303
     * The title for the most common HTTP status codes (`200`, `401`, `403`, `404`, `405`, `500`, `503`) is already configured.
304
     *
305
     * @param int $code The HTTP status code.
306
     * @param string|null $title [optional] The title of the HTML page.
307
     * @param string|null $message [optional] The message of the HTML page.
308
     *
309
     * @return void
310
     *
311
     * @since 1.2.5
312
     */
313 4
    public static function abort(int $code, ?string $title = null, ?string $message = null): void
314
    {
315
        $http = [
316
            200 => 'OK',
317
            401 => 'Unauthorized',
318
            403 => 'Forbidden',
319
            404 => 'Not Found',
320
            405 => 'Not Allowed',
321
            500 => 'Internal Server Error',
322
            503 => 'Service Unavailable',
323
        ];
324
325 4
        $title    = htmlspecialchars($title ?? $code . ' ' . $http[$code] ?? '', ENT_QUOTES, 'UTF-8');
326 4
        $message  = htmlspecialchars($message ?? '', ENT_QUOTES, 'UTF-8');
327
328
        try {
329 4
            $html = View::render((string)Config::get("global.errorPages.{$code}"), compact('code', 'title', 'message'));
330 1
        } catch (\Throwable $e) {
331 1
            $html = (new HTML(false))
332 1
                ->node('<!DOCTYPE html>')
333 1
                ->open('html', ['lang' => 'en'])
334 1
                    ->open('head')
335 1
                        ->title((string)$code)
336 1
                        ->link(null, [
337
                            'href' => 'https://cdn.jsdelivr.net/npm/bulma@latest/css/bulma.min.css',
338
                            'rel' => 'stylesheet'
339
                        ])
340 1
                    ->close()
341 1
                    ->open('body')
342 1
                        ->open('section', ['class' => 'section is-large has-text-centered'])
343 1
                            ->hr(null)
344 1
                            ->h1($title, ['class' => 'title is-1 is-spaced has-text-danger'])
345 1
                            ->condition(strlen($message))
346 1
                            ->h4($message, ['class' => 'subtitle'])
347 1
                            ->hr(null)
348 1
                            ->a('Reload', ['class' => 'button is-warning is-light', 'href' => 'javascript:location.reload();'])
349 1
                            ->entity('nbsp')
350 1
                            ->entity('nbsp')
351 1
                            ->a('Home', ['class' => 'button is-success is-light', 'href' => '/'])
352 1
                            ->hr(null)
353 1
                        ->close()
354 1
                    ->close()
355 1
                ->close()
356 1
            ->return();
357
        } finally {
358 4
            http_response_code($code);
359 4
            echo $html;
360
361 4
            static::terminate();
362
        }
363
    }
364
365
366
    /**
367
     * Terminates (exits) the PHP script.
368
     * This function is used instead of PHP `exit` to allow for testing `exit` without breaking the unit tests.
369
     *
370
     * @param int|string|null $status The exit status code/message.
371
     * @param bool $noShutdown Whether to not execute the shutdown function or not.
372
     *
373
     * @return void This function never returns. It will terminate the script.
374
     * @throws \Exception If `EXIT_EXCEPTION` is defined and truthy.
375
     *
376
     * @since 1.2.5
377
     */
378 5
    public static function terminate($status = null, bool $noShutdown = true): void
379
    {
380 5
        Event::dispatch(self::ON_TERMINATE);
381
382 5
        if (defined('EXIT_EXCEPTION') && EXIT_EXCEPTION) {
383 5
            throw new \Exception(empty($status) ? 'Exit' : 'Exit: ' . $status);
384
        }
385
386
        // @codeCoverageIgnoreStart
387
        if ($noShutdown) {
388
            // app shutdown function checks for this variable
389
            // to determine if it should exit, see bootstrap/loader.php
390
            Misc::setArrayValueByKey($GLOBALS, '_VELOX.TERMINATE', true);
391
        }
392
393
        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...
394
        // @codeCoverageIgnoreEnd
395
    }
396
397
    /**
398
     * Shuts the app down by terminating it and executing shutdown function(s).
399
     * The triggered shutdown functions can be normal shutdown functions registered,
400
     * using `register_shutdown_function()` or the `self::ON_SHUTDOWN` event.
401
     *
402
     * @return void
403
     *
404
     * @internal This method is to be used by the framework and not the user.
405
     * @since 1.4.2
406
     *
407
     * @codeCoverageIgnore
408
     */
409
    public static function shutdown(): void
410
    {
411
        Event::dispatch(self::ON_SHUTDOWN);
412
413
        Misc::setArrayValueByKey($GLOBALS, '_VELOX.SHUTDOWN', false);
414
415
        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...
416
    }
417
}
418