Passed
Push — master ( 6c6d7e...b48c4f )
by Marwan
01:39
created

App::terminate()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 3
c 2
b 0
f 0
nc 2
nop 1
dl 0
loc 7
ccs 3
cts 3
cp 1
crap 4
rs 10
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\Frontend\Data;
21
use MAKS\Velox\Frontend\View;
22
use MAKS\Velox\Frontend\HTML;
23
use MAKS\Velox\Frontend\Path;
24
use MAKS\Velox\Helper\Dumper;
25
use MAKS\Velox\Helper\Misc;
26
27
/**
28
 * A class that serves as a basic service-container for VELOX.
29
 * This class has most VELOX classes as public properties:
30
 * - `$event`: Instance of the `Event` class.
31
 * - `$config`: Instance of the `Config` class.
32
 * - `$router`: Instance of the `Router` class.
33
 * - `$globals`: Instance of the `Globals` class.
34
 * - `$session`: Instance of the `Session` class.
35
 * - `$database`: Instance of the `Database` class.
36
 * - `$data`: Instance of the `Data` class.
37
 * - `$view`: Instance of the `View` class.
38
 * - `$html`: Instance of the `HTML` class.
39
 * - `$path`: Instance of the `Path` class.
40
 * - `$dumper`: Instance of the `Dumper` class.
41
 * - `$misc`: Instance of the `Misc` class.
42
 *
43
 * Example:
44
 * ```
45
 * // create an instance
46
 * $app = new App();
47
 * // get an instance of the `Router` class via public property access notation
48
 * $app->router->handle('/dump', 'dd');
49
 * // or via calling a method with the same name
50
 * $app->router()->handle('/dump', 'dd');
51
 * ```
52
 *
53
 * @method static void handleException(\Throwable $expression) This function is available only at shutdown.
54
 * @method static void handleError(int $code, string $message, string $file, int $line) This function is available only at shutdown.
55
 *
56
 * @since 1.0.0
57
 */
58
class App
59
{
60
    public Event $event;
61
62
    public Config $config;
63
64
    public Router $router;
65
66
    public Globals $globals;
67
68
    public Session $session;
69
70
    public Database $database;
71
72
    public Data $data;
73
74
    public View $view;
75
76
    public HTML $html;
77
78
    public Path $path;
79
80
    public Dumper $dumper;
81
82
    public Misc $misc;
83
84
    protected array $methods;
85
86
    protected static array $staticMethods;
87
88
89
    /**
90
     * Class constructor.
91
     */
92 9
    public function __construct()
93
    {
94 9
        $this->event    = new Event();
95 9
        $this->config   = new Config();
96 9
        $this->router   = new Router();
97 9
        $this->globals  = new Globals();
98 9
        $this->session  = new Session();
99 9
        $this->database = Database::instance();
100 9
        $this->data     = new Data();
101 9
        $this->view     = new View();
102 9
        $this->html     = new HTML();
103 9
        $this->path     = new Path();
104 9
        $this->dumper   = new Dumper();
105 9
        $this->misc     = new Misc();
106 9
        $this->methods  = [];
107 9
    }
108
109 2
    public function __get(string $property)
110
    {
111 2
        $class = static::class;
112
113 2
        throw new \Exception("Call to undefined property {$class}::${$property}");
114
    }
115
116 3
    public function __call(string $method, array $arguments)
117
    {
118 3
        $class = static::class;
119
120
        try {
121 3
            return isset($this->methods[$method]) ? $this->methods[$method](...$arguments) : $this->{$method};
122 1
        } catch (\Exception $error) {
123 1
            throw new \Exception(
124 1
                "Call to undefined method {$class}::{$method}()",
125 1
                (int)$error->getCode(),
126
                $error
127
            );
128
        }
129
    }
130
131 2
    public static function __callStatic(string $method, array $arguments)
132
    {
133 2
        $class = static::class;
134
135 2
        if (!isset(static::$staticMethods[$method])) {
136 1
            throw new \Exception("Call to undefined static method {$class}::{$method}()");
137
        }
138
139 1
        return static::$staticMethods[$method](...$arguments);
140
    }
141
142
143
    /**
144
     * Extends the class using the passed callback.
145
     *
146
     * @param string $name Method name.
147
     * @param callable $callback The callback to use as method body.
148
     *
149
     * @return callable The created bound closure.
150
     */
151 1
    public function extend(string $name, callable $callback): callable
152
    {
153 1
        $method = \Closure::fromCallable($callback);
154 1
        $method = \Closure::bind($method, $this, $this);
155
156 1
        return $this->methods[$name] = $method;
157
    }
158
159
    /**
160
     * Extends the class using the passed callback.
161
     *
162
     * @param string $name Method name.
163
     * @param callable $callback The callback to use as method body.
164
     *
165
     * @return callable The created closure.
166
     */
167 1
    public static function extendStatic(string $name, callable $callback): callable
168
    {
169 1
        $method = \Closure::fromCallable($callback);
170 1
        $method = \Closure::bind($method, null, static::class);
171
172 1
        return static::$staticMethods[$name] = $method;
173
    }
174
175
    /**
176
     * Logs a message to a file and generates it if it does not exist.
177
     *
178
     * @param string $message The message wished to be logged.
179
     * @param array|null $context An associative array of values where array key = {key} in the message (context).
180
     * @param string|null $filename [optional] The name wished to be given to the file. If not provided `{global.logging.defaultFilename}` will be used instead.
181
     * @param string|null $directory [optional] The directory where the log file should be written. If not provided `{global.logging.defaultDirectory}` will be used instead.
182
     *
183
     * @return bool True on success (if the message was written).
184
     */
185 19
    public static function log(string $message, ?array $context = [], ?string $filename = null, ?string $directory = null): bool
186
    {
187 19
        if (!Config::get('global.logging.enabled', true)) {
188 1
            return true;
189
        }
190
191 19
        $hasPassed = false;
192
193 19
        if (!$filename) {
194 1
            $filename = Config::get('global.logging.defaultFilename', sprintf('autogenerated-%s', date('Ymd')));
195
        }
196
197 19
        if (!$directory) {
198 19
            $directory = Config::get('global.logging.defaultDirectory', BASE_PATH);
199
        }
200
201 19
        $file = Path::normalize($directory, $filename, '.log');
202
203 19
        if (!file_exists($directory)) {
204 1
            mkdir($directory, 0744, true);
205
        }
206
207
        // create log file if it does not exist
208 19
        if (!is_file($file) && is_writable($directory)) {
209 2
            $signature = 'Created by ' . __METHOD__ . date('() \o\\n l jS \of F Y h:i:s A (Ymdhis)') . PHP_EOL . PHP_EOL;
210 2
            file_put_contents($file, $signature, 0);
211 2
            chmod($file, 0775);
212
        }
213
214
        // write in the log file
215 19
        if (is_writable($file)) {
216 19
            clearstatcache(true, $file);
217
            // empty the file if it exceeds the configured file size
218 19
            $maxFileSize = Config::get('global.logging.maxFileSize', 6.4e+7);
219 19
            if (filesize($file) > $maxFileSize) {
220 1
                $stream = fopen($file, 'r');
221 1
                if (is_resource($stream)) {
222 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;
223 1
                    fclose($stream);
224 1
                    file_put_contents($file, $signature, 0);
225 1
                    chmod($file, 0775);
226
                }
227
            }
228
229 19
            $timestamp = (new \DateTime())->format(DATE_ISO8601);
230 19
            $message   = Misc::interpolate($message, $context ?? []);
231
232 19
            $log = "$timestamp\t$message\n";
233
234 19
            $stream = fopen($file, 'a+');
235 19
            if (is_resource($stream)) {
236 19
                fwrite($stream, $log);
237 19
                fclose($stream);
238 19
                $hasPassed = true;
239
            }
240
        }
241
242 19
        return $hasPassed;
243
    }
244
245
    /**
246
     * Aborts the current request and sends a response with the specified HTTP status code, title, and message.
247
     * An HTML page will be rendered with the specified title and message.
248
     * The title for the most common HTTP status codes (`200`, `403`, `404`, `405`, `500`, `503`) is already configured.
249
     *
250
     * @param int $code The HTTP status code.
251
     * @param string|null $title [optional] The title of the HTML page.
252
     * @param string|null $message [optional] The message of the HTML page.
253
     *
254
     * @return void
255
     *
256
     * @since 1.2.5
257
     */
258 3
    public static function abort(int $code, ?string $title = null, ?string $message = null): void
259
    {
260
        $http = [
261 3
            200 => 'OK',
262
            403 => 'Forbidden',
263
            404 => 'Not Found',
264
            405 => 'Not Allowed',
265
            500 => 'Internal Server Error',
266
            503 => 'Service Unavailable',
267
        ];
268
269 3
        http_response_code($code);
270
271 3
        $title    = htmlspecialchars($title ?? $code . ' ' . $http[$code] ?? '', ENT_QUOTES, 'UTF-8');
272 3
        $message  = htmlspecialchars($message ?? '', ENT_QUOTES, 'UTF-8');
273
274 3
        (new HTML(false))
275 3
            ->node('<!DOCTYPE html>')
276 3
            ->open('html', ['lang' => 'en'])
277 3
                ->open('head')
278 3
                    ->title((string)$code)
279 3
                    ->link(null, [
280 3
                        'href' => 'https://cdn.jsdelivr.net/npm/bulma@latest/css/bulma.min.css',
281
                        'rel' => 'stylesheet'
282
                    ])
283 3
                ->close()
284 3
                ->open('body')
285 3
                    ->open('section', ['class' => 'section is-large has-text-centered'])
286 3
                        ->hr(null)
287 3
                        ->h1($title, ['class' => 'title is-1 is-spaced has-text-danger'])
288 3
                        ->condition(strlen($message))
289 3
                        ->h4($message, ['class' => 'subtitle'])
290 3
                        ->hr(null)
291 3
                        ->a('Reload', ['class' => 'button is-warning is-light', 'href' => 'javascript:location.reload();'])
292 3
                        ->entity('nbsp')
293 3
                        ->entity('nbsp')
294 3
                        ->a('Home', ['class' => 'button is-success is-light', 'href' => '/'])
295 3
                        ->hr(null)
296 3
                    ->close()
297 3
                ->close()
298 3
            ->close()
299 3
        ->echo();
300
301 3
        static::terminate();
302
    }
303
304
305
    /**
306
     * Terminates (exits) the PHP script.
307
     * This function is used instead of PHP `exit` to allow for testing `exit` without breaking the unit tests.
308
     *
309
     * @param int|string|null $status The exit status code/message.
310
     *
311
     * @return void This function never returns. It will terminate the script.
312
     * @throws \Exception If `EXIT_EXCEPTION` is defined and truthy.
313
     *
314
     * @since 1.2.5
315
     */
316 4
    public static function terminate($status = null): void
317
    {
318 4
        if (defined('EXIT_EXCEPTION') && EXIT_EXCEPTION) {
319 4
            throw new \Exception(empty($status) ? 'Exit' : 'Exit: ' . $status);
320
        }
321
322
        exit($status); // @codeCoverageIgnore
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...
323
    }
324
}
325