Test Failed
Push — main ( e1affe...2e6d72 )
by Dimitri
14:06
created

is_online()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of Blitz PHP framework.
5
 *
6
 * (c) 2022 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
use BlitzPHP\Cli\Console\Console;
0 ignored issues
show
Bug introduced by
The type BlitzPHP\Cli\Console\Console was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use BlitzPHP\Config\Config;
14
use BlitzPHP\Container\Services;
15
use BlitzPHP\Contracts\Database\ConnectionInterface;
16
use BlitzPHP\Contracts\Http\StatusCode;
17
use BlitzPHP\Contracts\Session\CookieInterface;
18
use BlitzPHP\Contracts\Session\CookieManagerInterface;
19
use BlitzPHP\Exceptions\PageNotFoundException;
20
use BlitzPHP\Exceptions\RedirectException;
21
use BlitzPHP\Http\Redirection;
22
use BlitzPHP\Http\ServerRequest;
23
use BlitzPHP\Loader\Load;
24
use BlitzPHP\Session\Store;
25
use BlitzPHP\Utilities\Helpers;
26
use BlitzPHP\Utilities\Iterable\Collection;
27
use BlitzPHP\Utilities\Support\Invader;
28
29
// ================================= FONCTIONS UTIILITAIRES ESSENTIELLES ================================= //
30
31
if (! function_exists('env')) {
32
    /**
33
     * Obtient une variable d'environnement à partir des sources disponibles et fournit une émulation
34
     * pour les variables d'environnement non prises en charge ou incohérentes
35
     *
36
     * @param string     $key     Nom de la variable d'environnement
37
     * @param mixed|null $default
38
     *
39
     * @return string Paramétrage des variables d'environnement.
40
     */
41
    function env(string $key, $default = null)
42
    {
43 73
        return Helpers::env($key, $default);
44
    }
45
}
46
47
if (! function_exists('helper')) {
48
    /**
49
     * Charge un fichier d'aide en mémoire. Prend en charge les assistants d'espace de noms,
50
     * à la fois dans et hors du répertoire 'helpers' d'un répertoire à espace de noms.
51
     *
52
     * Chargera TOUS les helpers du nom correspondant, dans l'ordre suivant :
53
     *   1. app/Helpers
54
     *   2. {namespace}/Helpers
55
     *   3. system/Helpers
56
     */
57
    function helper(array|string $filenames)
58
    {
59 8
        Load::helper($filenames);
60
    }
61
}
62
63
if (! function_exists('model')) {
64
    /**
65
     * Simple maniere d'obtenir un modele.
66
     *
67
     * @template T
68
     *
69
     * @param array<class-string<T>>|class-string<T> $name
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<class-string<T>>|class-string<T> at position 2 could not be parsed: Unknown type name 'class-string' at position 2 in array<class-string<T>>|class-string<T>.
Loading history...
70
     *
71
     * @return T
72
     */
73
    function model(array|string $name, ?ConnectionInterface &$conn = null)
74
    {
75
        return Load::model($name, $conn);
0 ignored issues
show
Bug Best Practice introduced by
The expression return BlitzPHP\Loader\Load::model($name, $conn) also could return the type array<mixed,object> which is incompatible with the documented return type T.
Loading history...
76
    }
77
}
78
79
if (! function_exists('service')) {
80
    /**
81
     * Permet un accès plus propre au fichier de configuration des services.
82
     * Renvoie toujours une instance SHARED de la classe, donc l'appel de la fonction plusieurs fois renvera toujours la même instance.
83
     *
84
     * Ceux-ci sont égaux :
85
     *  - $cache = service('cache')
86
     *  - $cache = \BlitzPHP\Container\Services::cache();
87
     *
88
     * @template T
89
     *
90
     * @param class-string<T> $name
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<T> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<T>.
Loading history...
91
     *
92
     * @return object|T
93
     */
94
    function service(string $name, ...$params)
95
    {
96
        return Services::$name(...$params);
97
    }
98
}
99
100
if (! function_exists('single_service')) {
101
    /**
102
     * Autoriser l'accès propre à un service.
103
     * Renvoie toujours une nouvelle instance de la classe.
104
     *
105
     * @template T
106
     *
107
     * @param class-string<T> $name
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<T> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<T>.
Loading history...
108
     *
109
     * @return object|T
110
     */
111
    function single_service(string $name, ...$params)
112
    {
113
        // Assurez-vous qu'il ne s'agit PAS d'une instance partagée
114
        $params[] = false;
115
116
        return Services::$name(...$params);
117
    }
118
}
119
120
if (! function_exists('show404')) {
121
    /**
122
     * Afficher une page 404 introuvable dans le navigateur
123
     */
124
    function show404(string $message = 'The page you requested was not found.', string $heading = 'Page Not Found', array $params = [])
125
    {
126
        throw PageNotFoundException::pageNotFound($message);
127
    }
128
}
129
130
if (! function_exists('command')) {
131
    /**
132
     * Exécute une seule commande.
133
     * Entrée attendue dans une seule chaîne comme celle qui serait utilisée sur la ligne de commande elle-même :
134
     *
135
     *  > command('migrate:create SomeMigration');
136
     *
137
     * @see https://github.com/codeigniter4/CodeIgniter4/blob/b56c85c9d09fd3b34893220b2221ed27f8d508e6/system/Common.php#L133
138
     *
139
     * @return false|string
140
     */
141
    function command(string $command)
142
    {
143 2
        $regexString = '([^\s]+?)(?:\s|(?<!\\\\)"|(?<!\\\\)\'|$)';
144 2
        $regexQuoted = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')';
145
146 2
        $args   = [];
147 2
        $length = strlen($command);
148 2
        $cursor = 0;
149
150
        /**
151
         * Adopté de `StringInput::tokenize()` de Symfony avec quelques modifications.
152
         *
153
         * @see https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Console/Input/StringInput.php
154
         */
155
        while ($cursor < $length) {
156
            if (preg_match('/\s+/A', $command, $match, 0, $cursor)) {
157
                // Rien a faire
158
            } elseif (preg_match('/' . $regexQuoted . '/A', $command, $match, 0, $cursor)) {
159 2
                $args[] = stripcslashes(substr($match[0], 1, strlen($match[0]) - 2));
160
            } elseif (preg_match('/' . $regexString . '/A', $command, $match, 0, $cursor)) {
161 2
                $args[] = stripcslashes($match[1]);
162
            } else {
163
                // @codeCoverageIgnoreStart
164
                throw new InvalidArgumentException(sprintf(
165
                    'Impossible d\'analyser l\'entrée à proximité "... %s ...".',
166
                    substr($command, $cursor, 10)
167
                ));
168
                // @codeCoverageIgnoreEnd
169
            }
170
171 2
            $cursor += strlen($match[0]);
172
        }
173
174 2
        $command = array_shift($args);
175 2
        $params  = [];
176
177
        foreach ($args as $key => $arg) {
178
            if (mb_strpos($arg, '--') !== false) {
179 2
                unset($args[$key]);
180 2
                [$arg, $v]          = explode('=', $arg) + [1 => true];
181 2
                $params[trim($arg)] = is_string($v) ? trim($v) : $v;
182
            }
183
        }
184
185 2
        ob_start();
186 2
        Console::call($command, $args, $params);
187
188 2
        return ob_get_clean();
189
    }
190
}
191
192
if (! function_exists('config')) {
193
    /**
194
     * GET/SET App config
195
     *
196
     * @param mixed|null $default
197
     *
198
     * @return Config|mixed|void
199
     */
200
    function config(null|array|string $key = null, $default = null)
201
    {
202 99
        $config = Services::config();
203
204
        if (null === $key) {
205 2
            return $config;
206
        }
207
208
        if (is_string($key)) {
0 ignored issues
show
introduced by
The condition is_string($key) is always false.
Loading history...
209 99
            return $config->get($key, $default);
210
        }
211
212
        foreach ($key as $k => $v) {
213
            if (is_string($k)) {
214 6
                $config->set($k, $v);
215
            }
216
        }
217
    }
218
}
219
220
if (! function_exists('logger')) {
221
    /**
222
     * Une méthode de commodité pour les événements de journalisation via le système Log.
223
     *
224
     * Les niveaux de journal autorisés sont :
225
     *  - emergency
226
     *  - alert
227
     *  - critical
228
     *  - error
229
     *  - warning
230
     *  - notice
231
     *  - info
232
     *  - debug
233
     *
234
     * @param int|string $level
235
     *
236
     * @return \BlitzPHP\Debug\Logger|void
237
     */
238
    function logger($level = null, ?string $message = null, array $context = [])
239
    {
240
        $logger = Services::logger();
241
242
        if (empty($level) || empty($message)) {
243
            return $logger;
244
        }
245
246
        $logger->log($level, $message, $context);
247
    }
248
}
249
250
if (! function_exists('cache')) {
251
    /**
252
     * Une méthode pratique qui donne accès au cache
253
     * objet. Si aucun paramètre n'est fourni, renverra l'objet,
254
     * sinon, tentera de renvoyer la valeur mise en cache.
255
     *
256
     * Exemples:
257
     *    cache()->set('foo', 'bar'); ou cache('foo', 'bar');
258
     *    $foo = cache('bar');
259
     *
260
     * @param mixed|null $value
261
     *
262
     * @return \BlitzPHP\Cache\Cache|bool|mixed
263
     */
264
    function cache(?string $key = null, $value = null)
265
    {
266
        $cache = Services::cache();
267
268
        if (empty($key)) {
269
            return $cache;
270
        }
271
272
        if (empty($value)) {
273
            return $cache->get($key);
274
        }
275
276
        return $cache->set($key, $value);
277
    }
278
}
279
280
if (! function_exists('cookie')) {
281
    /**
282
     * Une méthode pratique qui donne accès à l'objet cookie.
283
     * Si aucun paramètre n'est fourni, renverra l'objet,
284
     * sinon, tentera de renvoyer la valeur du cookie.
285
     *
286
     * Exemples:
287
     *    cookie()->make('foo', 'bar'); ou cookie('foo', 'bar');
288
     *    $foo = cookie('bar')
289
     *
290
     * @return CookieInterface|CookieManagerInterface|null
291
     */
292
    function cookie(?string $name = null, null|array|string $value = null, int $minutes = 0, array $options = [])
293
    {
294 4
        $cookie = Services::cookie();
295
296
        if (null === $name) {
297
            return $cookie;
298
        }
299
300
        if (null === $value) {
301 4
            return $cookie->get($name);
302
        }
303
304 4
        return $cookie->make($name, $value, $minutes, $options);
305
    }
306
}
307
308
if (! function_exists('session')) {
309
    /**
310
     * Une méthode pratique pour accéder à l'instance de session, ou un élément qui a été défini dans la session.
311
     *
312
     * Exemples:
313
     *    session()->set('foo', 'bar');
314
     *    $foo = session('bar');
315
     *
316
     * @return array|bool|float|int|object|Store|string|null
317
     */
318
    function session(?string $val = null)
319
    {
320
        $session = Services::session();
321
322
        // Vous retournez un seul element ?
323
        if (is_string($val)) {
324
            return $session->get($val);
325
        }
326
327
        return $session;
328
    }
329
}
330
331
// =========================== FONCTIONS DE PREVENTION D'ATTAQUE =========================== //
332
333
if (! function_exists('esc')) {
334
    /**
335
     * Effectue un simple échappement automatique des données pour des raisons de sécurité.
336
     * Pourrait envisager de rendre cela plus complexe à une date ultérieure.
337
     *
338
     * Si $data est une chaîne, il suffit alors de l'échapper et de la renvoyer.
339
     * Si $data est un tableau, alors il boucle dessus, s'échappant de chaque
340
     * 'valeur' des paires clé/valeur.
341
     *
342
     * Valeurs de contexte valides : html, js, css, url, attr, raw, null
343
     *
344
     * @param array|string $data
345
     *
346
     * @return array|string
347
     *
348
     * @throws InvalidArgumentException
349
     */
350
    function esc($data, ?string $context = 'html', ?string $encoding = null)
351
    {
352
        if (class_exists('\Laminas\Escaper\Escaper')) {
353 56
            return Helpers::esc($data, $context, $encoding);
354
        }
355
356 56
        return h($data, true, $encoding);
357
    }
358
}
359
360
if (! function_exists('h')) {
361
    /**
362
     * Méthode pratique pour htmlspecialchars.
363
     *
364
     * @param mixed       $text    Texte à envelopper dans htmlspecialchars. Fonctionne également avec des tableaux et des objets.
365
     *                             Les tableaux seront mappés et tous leurs éléments seront échappés. Les objets seront transtypés s'ils
366
     *                             implémenter une méthode `__toString`. Sinon, le nom de la classe sera utilisé.
367
     *                             Les autres types de scalaires seront renvoyés tels quels.
368
     * @param bool        $double  Encodez les entités html existantes.
369
     * @param string|null $charset Jeu de caractères à utiliser lors de l'échappement. La valeur par défaut est la valeur de configuration dans `mb_internal_encoding()` ou 'UTF-8'.
370
     *
371
     * @return mixed Texte enveloppé.
372
     */
373
    function h($text, bool $double = true, ?string $charset = null)
374
    {
375 56
        return Helpers::h($text, $double, $charset);
376
    }
377
}
378
379
if (! function_exists('purify')) {
380
    /**
381
     * Purifiez l'entrée à l'aide de la classe autonome HTMLPurifier.
382
     * Utilisez facilement plusieurs configurations de purificateur.
383
     *
384
     * @param string|string[] $dirty_html
385
     * @param false|string    $config
386
     *
387
     * @return string|string[]
388
     */
389
    function purify($dirty_html, $config = false)
390
    {
391
        return Helpers::purify($dirty_html, $config);
392
    }
393
}
394
395
if (! function_exists('remove_invisible_characters')) {
396
    /**
397
     * Supprimer les caractères invisibles
398
     *
399
     * Cela empêche de prendre en sandwich des caractères nuls
400
     * entre les caractères ascii, comme Java\0script.
401
     */
402
    function remove_invisible_characters(string $str, bool $url_encoded = true): string
403
    {
404
        return Helpers::removeInvisibleCharacters($str, $url_encoded);
405
    }
406
}
407
408
if (! function_exists('stringify_attributes')) {
409
    /**
410
     * Chaîner les attributs à utiliser dans les balises HTML.
411
     *
412
     * @param array|object|string $attributes
413
     */
414
    function stringify_attributes($attributes, bool $js = false): string
415
    {
416
        return Helpers::stringifyAttributes($attributes, $js);
417
    }
418
}
419
420
// ================================= FONCTIONS D'ENVIRONNEMENT D'EXECUTION ================================= //
421
422
if (! function_exists('environment')) {
423
    /**
424
     * Renvoi l'environnement d'execution actuel ou determine si on est dans un environnement specifie
425
     *
426
     * @return bool|string
427
     */
428
    function environment(null|array|string $env)
429
    {
430 13
        $current = env('ENVIRONMENT');
431
        if (empty($current) || $current === 'auto') {
432 13
            $current = config('app.environment');
433
        }
434
435
        if (empty($env)) {
436
            return $current;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $current also could return the type BlitzPHP\Config\Config which is incompatible with the documented return type boolean|string.
Loading history...
437
        }
438
439
        $envMap = [
440
            'dev'     => 'development',
441
            'local'   => 'development',
442
            'prod'    => 'production',
443
            'test'    => 'testing',
444
            'stage'   => 'testing',
445
            'staging' => 'testing',
446 13
        ];
447
448 13
        $current = $envMap[$current] ?? $current;
449
450
        if (is_string($env)) {
0 ignored issues
show
introduced by
The condition is_string($env) is always false.
Loading history...
451 2
            $env = [$env];
452
        }
453
454 13
        $env = array_map(static fn ($k) => $envMap[$k] ?? $k, $env);
455
456 13
        return in_array($current, $env, true);
457
    }
458
}
459
460
if (! function_exists('on_dev')) {
461
    /**
462
     * Testez pour voir si nous sommes dans un environnement de développement.
463
     */
464
    function on_dev(bool $checkOnline = false): bool
465
    {
466
        if ($checkOnline && is_online()) {
467
            return false;
468
        }
469
470 4
        return environment(['dev', 'development', 'local']);
471
    }
472
}
473
474
if (! function_exists('on_prod')) {
475
    /**
476
     * Testez pour voir si nous sommes dans un environnement de production.
477
     */
478
    function on_prod(bool $checkOnline = false): bool
479
    {
480
        if ($checkOnline && is_online()) {
481
            return true;
482
        }
483
484
        return environment(['prod', 'production']);
485
    }
486
}
487
488
if (! function_exists('on_test')) {
489
    /**
490
     * Testez pour voir si nous sommes dans un environnement de test
491
     */
492
    function on_test(): bool
493
    {
494 7
        return environment(['test', 'testing', 'stage', 'staging']);
495
    }
496
}
497
498
if (! function_exists('is_cli')) {
499
    /**
500
     * Testez pour voir si une demande a été faite à partir de la ligne de commande.
501
     */
502
    function is_cli(): bool
503
    {
504
        return Helpers::isCli();
505
    }
506
}
507
508
if (! function_exists('is_php')) {
509
    /**
510
     * Détermine si la version actuelle de PHP est égale ou supérieure à la valeur fournie.
511
     */
512
    function is_php(string $version): bool
513
    {
514
        return Helpers::isPhp($version);
515
    }
516
}
517
518
if (! function_exists('is_windows')) {
519
    /**
520
     * Déterminez si l'environnement actuel est basé sur Windows.
521
     */
522
    function is_windows(): bool
523
    {
524
        return PHP_OS_FAMILY === 'Windows';
525
    }
526
}
527
528
if (! function_exists('is_https')) {
529
    /**
530
     * Determines if the application is accessed via an encrypted * (HTTPS) connection.
531
     */
532
    function is_https(): bool
533
    {
534
        return Services::request()->is('ssl');
535
    }
536
}
537
538
if (! function_exists('is_localfile')) {
539
    /**
540
     * Vérifiez si le fichier auquel vous souhaitez accéder est un fichier local de votre application ou non
541
     */
542
    function is_localfile(string $name): bool
543
    {
544
        if (preg_match('#^' . base_url() . '#i', $name)) {
545
            return true;
546
        }
547
548
        return ! preg_match('#^(https?://)#i', $name);
549
    }
550
}
551
552
if (! function_exists('is_online')) {
553
    /**
554
     * Tester si l'application s'exécute en local ou en ligne.
555
     */
556
    function is_online(): bool
557
    {
558 2
        return Helpers::isOnline();
559
    }
560
}
561
562
if (! function_exists('is_connected')) {
563
    /**
564
     * Verifie si l'utilisateur a une connexion internet active.
565
     */
566
    function is_connected(): bool
567
    {
568
        return Helpers::isConnected();
569
    }
570
}
571
572
if (! function_exists('is_ajax_request')) {
573
    /**
574
     * Testez pour voir si une requête contient l'en-tête HTTP_X_REQUESTED_WITH.
575
     */
576
    function is_ajax_request(): bool
577
    {
578
        return Services::request()->is('ajax');
579
    }
580
}
581
582
if (! function_exists('redirection')) {
583
    /**
584
     * Redirige l'utilisateur
585
     */
586
    function redirection(string $uri = '', string $method = 'location', ?int $code = 302)
587
    {
588
        $response = redirect()->to($uri, $code, [], null, $method);
589
590
        Services::emitter()->emitHeaders($response);
591
592
        exit(EXIT_SUCCESS);
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...
593
    }
594
}
595
596
if (! function_exists('redirect')) {
597
    /**
598
     * Méthode pratique qui fonctionne avec la $request globale actuelle et
599
     * l'instance $router à rediriger à l'aide de routes nommées et le routage inversé
600
     * pour déterminer l'URL à laquelle aller. Si rien n'est trouvé, traitera
601
     * comme une redirection traditionnelle et passez la chaîne, en laissant
602
     * $redirection->redirect() détermine la méthode et le code corrects.
603
     *
604
     * Si plus de contrôle est nécessaire, vous devez utiliser explicitement $response->redirect.
605
     */
606
    function redirect(?string $uri = null): Redirection
607
    {
608
        $redirection = Services::redirection();
609
610
        if (! empty($uri)) {
611
            return $redirection->route($uri);
612
        }
613
614
        return $redirection;
615
    }
616
}
617
618
if (! function_exists('back')) {
619
    /**
620
     * Retourne a la page precedente
621
     *
622
     * @param mixed $fallback
623
     */
624
    function back(int $code = 302, array $headers = [], $fallback = false): Redirection
625
    {
626
        return redirect()->back($code, $headers, $fallback);
627
    }
628
}
629
630
if (! function_exists('link_to')) {
631
    /**
632
     * Étant donné une chaîne de contrôleur/méthode et tous les paramètres,
633
     * tentera de créer l'URL relative à la route correspondante.
634
     *
635
     * REMARQUE : Cela nécessite que le contrôleur/la méthode
636
     * ait une route définie dans le fichier de configuration des routes.
637
     */
638
    function link_to(string $method, ...$params): string
639
    {
640
        $url = Services::routes()->reverseRoute($method, ...$params);
641
642
        if (empty($url)) {
643
            return '';
644
        }
645
646
        return site_url($url);
647
    }
648
}
649
650
if (! function_exists('clean_path')) {
651
    /**
652
     * Une méthode pratique pour nettoyer les chemins pour
653
     * une sortie plus belle. Utile pour les exceptions
654
     * gestion, journalisation des erreurs, etc.
655
     */
656
    function clean_path(string $path): string
657
    {
658 2
        $path = realpath($path) ?: $path;
659
660
        switch (true) {
661
            case str_starts_with($path, APP_PATH)  :
662 2
                return 'APP_PATH' . DS . substr($path, strlen(APP_PATH));
663
664
            case str_starts_with($path, SYST_PATH)  :
665 2
                return 'SYST_PATH' . DS . substr($path, strlen(SYST_PATH));
666
667
            case defined('VENDOR_PATH') && str_starts_with($path, VENDOR_PATH . 'blitz-php' . DS)  :
668 2
                return 'BLITZ_PATH' . DS . substr($path, strlen(VENDOR_PATH . 'blitz-php' . DS));
669
670
            case defined('VENDOR_PATH') && str_starts_with($path, VENDOR_PATH)  :
671 2
                return 'VENDOR_PATH' . DS . substr($path, strlen(VENDOR_PATH));
672
673
            case str_starts_with($path, ROOTPATH)  :
674 2
                return 'ROOTPATH' . DS . substr($path, strlen(ROOTPATH));
675
676
            default:
677
                return $path;
678
        }
679
    }
680
}
681
682
if (! function_exists('old')) {
683
    /**
684
     * Fournit l'accès à "entrée ancienne" qui a été définie dans la session lors d'un redirect()-withInput().
685
     *
686
     * @param false|string $escape
687
     * @param mixed|null   $default
688
     * @phpstan-param false|'attr'|'css'|'html'|'js'|'raw'|'url' $escape
689
     *
690
     * @return array|string|null
691
     */
692
    function old(string $key, $default = null, $escape = 'html')
693
    {
694
        // Assurez-vous de charger la session
695
        if (session_status() === PHP_SESSION_NONE && ! on_test()) {
696
            session(); // @codeCoverageIgnore
697
        }
698
699
        // Retourne la valeur par défaut si rien n'a été trouvé dans l'ancien input.
700
        if (null === $value = Services::request()->old($key)) {
701
            return $default;
702
        }
703
704
        return $escape === false ? $value : esc($value, $escape);
705
    }
706
}
707
708
// ================================= FONCTIONS DE DEBOGAGE ================================= //
709
710
if (! function_exists('deprecationWarning')) {
711
    /**
712
     * Méthode d'assistance pour générer des avertissements d'obsolescence
713
     *
714
     * @param string $message    Le message à afficher comme avertissement d'obsolescence.
715
     * @param int    $stackFrame Le cadre de pile à inclure dans l'erreur. Par défaut à 1
716
     *                           car cela devrait pointer vers le code de l'application/du plugin.
717
     *
718
     * @return void
719
     */
720
    function deprecation_warning(string $message, int $stackFrame = 1)
721
    {
722
        Helpers::deprecationWarning($message, $stackFrame);
723
    }
724
}
725
726
if (! function_exists('pr')) {
727
    /**
728
     * print_r() convenience function.
729
     *
730
     * In terminals this will act similar to using print_r() directly, when not run on cli
731
     * print_r() will also wrap <pre> tags around the output of given variable. Similar to debug().
732
     *
733
     * This function returns the same variable that was passed.
734
     *
735
     * @param mixed $var Variable to print out.
736
     *
737
     * @return mixed the same $var that was passed to this function
738
     */
739
    function pr($var)
740
    {
741
        $template = (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg') ? '<pre class="pr">%s</pre>' : "\n%s\n\n";
742
        printf($template, trim(print_r($var, true)));
0 ignored issues
show
Bug introduced by
It seems like print_r($var, true) can also be of type true; however, parameter $string of trim() 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

742
        printf($template, trim(/** @scrutinizer ignore-type */ print_r($var, true)));
Loading history...
743
744
        return $var;
745
    }
746
}
747
748
if (! function_exists('pj')) {
749
    /**
750
     * json pretty print convenience function.
751
     *
752
     * In terminals this will act similar to using json_encode() with JSON_PRETTY_PRINT directly, when not run on cli
753
     * will also wrap <pre> tags around the output of given variable. Similar to pr().
754
     *
755
     * This function returns the same variable that was passed.
756
     *
757
     * @param mixed $var Variable to print out.
758
     *
759
     * @return mixed the same $var that was passed to this function
760
     *
761
     * @see pr()
762
     */
763
    function pj($var)
764
    {
765
        return Helpers::pj($var);
766
    }
767
}
768
769
if (! function_exists('trigger_warning')) {
770
    /**
771
     * Déclenche un E_USER_WARNING.
772
     */
773
    function trigger_warning(string $message)
774
    {
775
        Helpers::triggerWarning($message);
776
    }
777
}
778
779
// ================================= FONCTIONS DIVERSES ================================= //
780
781
if (! function_exists('force_https')) {
782
    /**
783
     * Utilisé pour forcer l'accès à une page via HTTPS.
784
     * Utilise une redirection standard, plus définira l'en-tête HSTS
785
     * pour les navigateurs modernes qui prennent en charge, ce qui donne une meilleur
786
     * protection contre les attaques de l'homme du milieu.
787
     *
788
     * @see https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security
789
     *
790
     * @param int $duration Combien de temps l'en-tête SSL doit-il être défini ? (en secondes)
791
     *                      Par défaut à 1 an.
792
     *
793
     * @credit CodeIgniter <a href="http://codeigniter.com/">helpers force_https() - /system/Common.php</a>
794
     *
795
     * @throws RedirectException
796
     */
797
    function force_https(int $duration = 31536000, ?ServerRequest $request = null, ?Redirection $response = null)
798
    {
799
        $request ??= Services::request();
800
        $response ??= Services::redirection();
801
802
        if (is_cli() || $request->is('ssl')) {
803
            return;
804
        }
805
806
        // Si la session est active, nous devons régénérer
807
        // l'ID de session pour des raisons de sécurité.
808
        if (! on_test() && session_status() === PHP_SESSION_ACTIVE) {
809
            Services::session()->regenerate(); // @codeCoverageIgnore
810
        }
811
812
        $uri = (string) $request->getUri()->withScheme('https');
813
814
        // Définir un en-tête HSTS
815
        $response = $response->to($uri)
816
            ->withStatus(StatusCode::TEMPORARY_REDIRECT)
817
            ->withHeader('Strict-Transport-Security', 'max-age=' . $duration)
818
            ->withStringBody('');
819
820
        throw new RedirectException($response);
821
    }
822
}
823
824
if (! function_exists('get_type_name')) {
825
    /**
826
     * Renvoie la classe d'objets ou le type var de ce n'est pas un objet
827
     *
828
     * @param mixed $var Variable à vérifier
829
     *
830
     * @return string Renvoie le nom de la classe ou le type de variable
831
     */
832
    function get_type_name($var): string
833
    {
834
        return Helpers::typeName($var);
835
    }
836
}
837
838
if (! function_exists('ip_address')) {
839
    /**
840
     * Renvoie l'adresse IP de l'utilisateur actuel
841
     */
842
    function ip_address(): string
843
    {
844
        return (string) Services::request()->clientIp();
845
    }
846
}
847
848
if (! function_exists('is_really_writable')) {
849
    /**
850
     * Tests d'inscriptibilité des fichiers
851
     */
852
    function is_really_writable(string $file): bool
853
    {
854
        return Helpers::isReallyWritable($file);
855
    }
856
}
857
858
if (! function_exists('lang')) {
859
    /**
860
     * Une méthode pratique pour traduire une chaîne ou un tableau d'entrées et formater
861
     * le résultat avec le MessageFormatter de l'extension intl.
862
     */
863
    function lang(string $line, array $args = [], ?string $locale = null): string
864
    {
865 20
        return Services::translator($locale)->getLine($line, $args);
866
    }
867
}
868
869
if (! function_exists('__')) {
870
    /**
871
     * Une méthode pratique pour traduire une chaîne ou un tableau d'entrées et formater
872
     * le résultat avec le MessageFormatter de l'extension intl.
873
     */
874
    function __(string $line, array $args = [], ?string $locale = null): string
875
    {
876
        $tranlation = lang('App.' . $line, $args, $locale);
877
878
        return preg_replace('/^(App\.)/i', '', $tranlation);
879
    }
880
}
881
882
if (! function_exists('namespace_split')) {
883
    /**
884
     * Séparez l'espace de noms du nom de classe.
885
     *
886
     * Couramment utilisé comme `list($namespace, $className) = namespaceSplit($class);`.
887
     *
888
     * @param string $class Le nom complet de la classe, ie `BlitzPHP\Http\Request`.
889
     *
890
     * @return array Tableau avec 2 index. 0 => namespace, 1 => classname.
891
     */
892
    function namespace_split(string $class): array
893
    {
894
        $pos = strrpos($class, '\\');
895
        if ($pos === false) {
896
            return ['', $class];
897
        }
898
899
        return [substr($class, 0, $pos), substr($class, $pos + 1)];
900
    }
901
}
902
903
if (! function_exists('view_exist')) {
904
    /**
905
     * Verifie si un fichier de vue existe. Utile pour limiter les failles include
906
     */
907
    function view_exist(string $name, ?string $ext = null, array $options = []): bool
908
    {
909
        return Services::viewer()->exists($name, $ext, $options);
910
    }
911
}
912
913
if (! function_exists('view')) {
914
    /**
915
     * Charge une vue
916
     *
917
     * @return \BlitzPHP\View\View
918
     */
919
    function view(string $view, array $data = [], array $options = [])
920
    {
921
        return Services::viewer()->make($view, $data, $options);
922
    }
923
}
924
925
if (! function_exists('flash')) {
926
    /**
927
     * Fournisseur d'acces rapide a la classe PHP Flash
928
     *
929
     * @return FlashMessages|string
930
     */
931
    /*
932
    function flash()
933
    {
934
         @var FlashMessages $flash
935
        $flash = service(FlashMessages::class);
936
937
        $params = func_get_args();
938
        $type = array_shift($params);
939
940
        if (!empty($type)) {
941
            if (empty($params)) {
942
                if ($type === 'all') {
943
                    $type = null;
944
                }
945
                return $flash->display($type, false);
946
            }
947
948
            $message = array_shift($params);
949
950
            return $flash->add($message, $type, ...$params);
951
        }
952
953
        return $flash;
954
    }*/
955
}
956
957
if (! function_exists('geo_ip')) {
958
    /**
959
     * Recuperation des coordonnees (pays, ville, etc) d'un utilisateur en fonction de son ip
960
     */
961
    function geo_ip(?string $ip = null): ?array
962
    {
963
        return json_decode(file_get_contents('http://ip-api.com/json/' . $ip), true);
964
    }
965
}
966
967
if (! function_exists('to_stream')) {
968
    /**
969
     * Créez un nouveau flux basé sur le type d'entrée.
970
     *
971
     * Options est un tableau associatif pouvant contenir les clés suivantes :
972
     * - metadata : Tableau de métadonnées personnalisées.
973
     * - size : Taille du flux.
974
     *
975
     * @param bool|callable|float|int|\Iterator|\Psr\Http\Message\StreamInterface|resource|string|null $resource Données du corps de l'entité
976
     * @param array                                                                                    $options  Additional options
977
     *
978
     * @uses GuzzleHttp\Psr7\stream_for
979
     *
980
     * @throws \InvalidArgumentException si l'argument $resource n'est pas valide.
981
     */
982
    function to_stream($resource = '', array $options = []): Psr\Http\Message\StreamInterface
983
    {
984 2
        return \GuzzleHttp\Psr7\Utils::streamFor($resource, $options);
985
    }
986
}
987
988
if (! function_exists('value')) {
989
    /**
990
     * Renvoie la valeur par défaut de la valeur donnée.
991
     */
992
    function value(mixed $value, ...$args): mixed
993
    {
994
        return Helpers::value($value, ...$args);
995
    }
996
}
997
998
if (! function_exists('collect')) {
999
    /**
1000
     * Créez une collection à partir de la valeur donnée.
1001
     */
1002
    function collect(mixed $value = null): Collection
1003
    {
1004
        return Helpers::collect($value);
1005
    }
1006
}
1007
1008
if (! function_exists('with')) {
1009
    /**
1010
     * Renvoie la valeur donnée, éventuellement transmise via le rappel donné.
1011
     *
1012
     * @param mixed $value
1013
     */
1014
    function with($value, ?callable $callback = null): mixed
1015
    {
1016
        return Helpers::with($value, $callback);
1017
    }
1018
}
1019
1020
if (! function_exists('tap')) {
1021
    /**
1022
     * Appelez la Closure donnée avec cette instance puis renvoyez l'instance.
1023
     */
1024
    function tap(mixed $value, ?callable $callback = null): mixed
1025
    {
1026
        return Helpers::tap($value, $callback);
1027
    }
1028
}
1029
1030
if (! function_exists('last')) {
1031
    /**
1032
     * Recupere le dernier element d'un tableau
1033
     */
1034
    function last(array|object $array)
1035
    {
1036
        return end($array);
1037
    }
1038
}
1039
1040
if (! function_exists('invade')) {
1041
    /**
1042
     * Cette classe offre une fonction d'invasion qui vous permettra de lire / écrire des propriétés privées d'un objet.
1043
     * Il vous permettra également de définir, obtenir et appeler des méthodes privées.
1044
     *
1045
     * @return Invader
1046
     *
1047
     * @see https://github.com/spatie/invade/blob/main/src/Invader.php
1048
     */
1049
    function invade(object $object)
1050
    {
1051
        return Invader::make($object);
1052
    }
1053
}
1054