Passed
Push — main ( 40dc38...b0a2e6 )
by Dimitri
11:06
created

old()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 5
c 0
b 0
f 0
nc 6
nop 3
dl 0
loc 13
rs 9.6111
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\Config\Config;
13
use BlitzPHP\Contracts\Database\ConnectionInterface;
14
use BlitzPHP\Exceptions\PageNotFoundException;
15
use BlitzPHP\Http\Redirection;
16
use BlitzPHP\Http\ServerRequest;
17
use BlitzPHP\Http\Uri;
18
use BlitzPHP\Loader\Load;
19
use BlitzPHP\Loader\Services;
20
use BlitzPHP\Session\Session;
21
use BlitzPHP\Utilities\Helpers;
22
use BlitzPHP\Utilities\Iterable\Collection;
23
use Kint\Kint;
24
25
// ================================= FONCTIONS D'ACCESSIBILITE ================================= //
26
27
if (! function_exists('env')) {
28
    /**
29
     * Obtient une variable d'environnement à partir des sources disponibles et fournit une émulation
30
     * pour les variables d'environnement non prises en charge ou incohérentes
31
     *
32
     * @param string     $key     Nom de la variable d'environnement
33
     * @param mixed|null $default
34
     *
35
     * @return string Paramétrage des variables d'environnement.
36
     */
37
    function env(string $key, $default = null)
38
    {
39
        return Helpers::env($key, $default);
40
    }
41
}
42
43
if (! function_exists('helper')) {
44
    /**
45
     * Charge un fichier d'aide en mémoire. Prend en charge les assistants d'espace de noms,
46
     * à la fois dans et hors du répertoire 'helpers' d'un répertoire à espace de noms.
47
     *
48
     * Chargera TOUS les assistants du nom correspondant, dans l'ordre suivant :
49
     *   1. app/Helpers
50
     *   2. {namespace}/Helpers
51
     *   3. system/Helpers
52
     *
53
     * @param array|string $filenames
54
     */
55
    function helper($filenames)
56
    {
57
        Load::helper($filenames);
58
    }
59
}
60
61
if (! function_exists('model')) {
62
    /**
63
     * Simple maniere d'obtenir un modele.
64
     *
65
     * @template T of BlitzPHP\Models\BaseModel
66
     *
67
     * @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...
68
     *
69
     * @return T
70
     */
71
    function model(string|array $name, ?ConnectionInterface &$conn = null)
72
    {
73
        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...
74
    }
75
}
76
77
if (! function_exists('service')) {
78
    /**
79
     * Permet un accès plus propre au fichier de configuration des services.
80
     * Renvoie toujours une instance SHARED de la classe, donc
81
     * appeler la fonction plusieurs fois doit toujours
82
     * renvoie la même instance.
83
     *
84
     * Ceux-ci sont égaux :
85
     *  - $cache = service('cache')
86
     *  - $cache = \BlitzPHP\Loader\Services::cache();
87
     */
88
    function service(string $name, ...$params)
89
    {
90
        return Services::$name(...$params);
91
    }
92
}
93
94
if (! function_exists('single_service')) {
95
    /**
96
     * Autoriser l'accès propre à un service.
97
     * Renvoie toujours une nouvelle instance de la classe.
98
     */
99
    function single_service(string $name, ...$params)
100
    {
101
        // Assurez-vous qu'il ne s'agit PAS d'une instance partagée
102
        $params[] = false;
103
104
        return Services::$name(...$params);
105
    }
106
}
107
108
if (! function_exists('show404')) {
109
    /**
110
     * Afficher une page 404 introuvable dans le navigateur
111
     */
112
    function show404(string $message = 'The page you requested was not found.', string $heading = 'Page Not Found', array $params = [])
113
    {
114
        throw PageNotFoundException::pageNotFound($message);
115
    }
116
}
117
118
if (! function_exists('config')) {
119
    /**
120
     * GET/SET App config
121
     *
122
     * @param mixed $value
123
     *
124
     * @return mixed
125
     */
126
    function config(string $config, $value = null, bool $force_set = false)
127
    {
128
        if (! empty($value) || (empty($value) && true === $force_set)) {
129
            Config::set($config, $value);
130
        }
131
132
        return Config::get($config);
133
    }
134
}
135
136
// =========================== FONCTIONS DE PREVENTION D'ATTAQUE =========================== //
137
138
if (! function_exists('esc')) {
139
    /**
140
     * Effectue un simple échappement automatique des données pour des raisons de sécurité.
141
     * Pourrait envisager de rendre cela plus complexe à une date ultérieure.
142
     *
143
     * Si $data est une chaîne, il suffit alors de l'échapper et de la renvoyer.
144
     * Si $data est un tableau, alors il boucle dessus, s'échappant de chaque
145
     * 'valeur' des paires clé/valeur.
146
     *
147
     * Valeurs de contexte valides : html, js, css, url, attr, raw, null
148
     *
149
     * @param array|string $data
150
     *
151
     * @return array|string
152
     *
153
     * @throws InvalidArgumentException
154
     */
155
    function esc($data, ?string $context = 'html', ?string $encoding = null)
156
    {
157
        if (class_exists('\Laminas\Escaper\Escaper')) {
158
            return Helpers::esc($data, $context, $encoding);
159
        }
160
161
        return h($data, true, $encoding);
162
    }
163
}
164
165
if (! function_exists('h')) {
166
    /**
167
     * Méthode pratique pour htmlspecialchars.
168
     *
169
     * @param mixed       $text    Texte à envelopper dans htmlspecialchars. Fonctionne également avec des tableaux et des objets.
170
     *                             Les tableaux seront mappés et tous leurs éléments seront échappés. Les objets seront transtypés s'ils
171
     *                             implémenter une méthode `__toString`. Sinon, le nom de la classe sera utilisé.
172
     *                             Les autres types de scalaires seront renvoyés tels quels.
173
     * @param bool        $double  Encodez les entités html existantes.
174
     * @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'.
175
     *
176
     * @return mixed Texte enveloppé.
177
     */
178
    function h($text, bool $double = true, ?string $charset = null)
179
    {
180
        return Helpers::h($text, $double, $charset);
181
    }
182
}
183
184
if (! function_exists('purify')) {
185
    /**
186
     * Purifiez l'entrée à l'aide de la classe autonome HTMLPurifier.
187
     * Utilisez facilement plusieurs configurations de purificateur.
188
     *
189
     * @param string|string[]
190
     * @param false|string
191
     * @param mixed $dirty_html
192
     * @param mixed $config
193
     *
194
     * @return string|string[]
195
     */
196
    function purify($dirty_html, $config = false)
197
    {
198
        return Helpers::purify($dirty_html, $config);
199
    }
200
}
201
202
if (! function_exists('remove_invisible_characters')) {
203
    /**
204
     * Supprimer les caractères invisibles
205
     *
206
     * Cela empêche de prendre en sandwich des caractères nuls
207
     * entre les caractères ascii, comme Java\0script.
208
     */
209
    function remove_invisible_characters(string $str, bool $url_encoded = true): string
210
    {
211
        return Helpers::removeInvisibleCharacters($str, $url_encoded);
212
    }
213
}
214
215
if (! function_exists('stringify_attributes')) {
216
    /**
217
     * Chaîner les attributs à utiliser dans les balises HTML.
218
     *
219
     * @param array|object|string $attributes
220
     */
221
    function stringify_attributes($attributes, bool $js = false): string
222
    {
223
        return Helpers::stringifyAttributes($attributes, $js);
224
    }
225
}
226
227
// ================================= FONCTIONS D'ENVIRONNEMENT D'EXECUTION ================================= //
228
229
if (! function_exists('on_dev')) {
230
    /**
231
     * Testez pour voir si nous sommes dans un environnement de développement.
232
     */
233
    function on_dev(bool $checkOnline = false): bool
234
    {
235
        if ($checkOnline && is_online()) {
236
            return false;
237
        }
238
239
        $env = config('app.environment');
240
241
        return in_array($env, ['dev', 'development'], true);
242
    }
243
}
244
245
if (! function_exists('on_prod')) {
246
    /**
247
     * Testez pour voir si nous sommes dans un environnement de production.
248
     */
249
    function on_prod(bool $checkOnline = false): bool
250
    {
251
        if ($checkOnline && is_online()) {
252
            return true;
253
        }
254
255
        $env = config('app.environment');
256
257
        return in_array($env, ['prod', 'production'], true);
258
    }
259
}
260
261
if (! function_exists('on_test')) {
262
    /**
263
     * Testez pour voir si nous sommes dans un environnement de test
264
     */
265
    function on_test(): bool
266
    {
267
        $env = config('app.environment');
268
269
        return in_array($env, ['test', 'testing'], true);
270
    }
271
}
272
273
if (! function_exists('is_cli')) {
274
    /**
275
     * Testez pour voir si une demande a été faite à partir de la ligne de commande.
276
     */
277
    function is_cli(): bool
278
    {
279
        return Helpers::isCli();
280
    }
281
}
282
283
if (! function_exists('is_php')) {
284
    /**
285
     * Détermine si la version actuelle de PHP est égale ou supérieure à la valeur fournie.
286
     */
287
    function is_php(string $version): bool
288
    {
289
        return Helpers::isPhp($version);
290
    }
291
}
292
293
if (! function_exists('is_windows')) {
294
    /**
295
     * Déterminez si l'environnement actuel est basé sur Windows.
296
     */
297
    function is_windows(): bool
298
    {
299
        return PHP_OS_FAMILY === 'Windows';
300
    }
301
}
302
303
if (! function_exists('is_https')) {
304
    /**
305
     * Determines if the application is accessed via an encrypted * (HTTPS) connection.
306
     */
307
    function is_https(): bool
308
    {
309
        return Services::request()->is('ssl');
310
    }
311
}
312
313
if (! function_exists('is_localfile')) {
314
    /**
315
     * Vérifiez si le fichier auquel vous souhaitez accéder est un fichier local de votre application ou non
316
     */
317
    function is_localfile(string $name): bool
318
    {
319
        if (preg_match('#^' . base_url() . '#i', $name)) {
320
            return true;
321
        }
322
323
        return ! preg_match('#^(https?://)#i', $name);
324
    }
325
}
326
327
if (! function_exists('is_online')) {
328
    /**
329
     * Tester si l'application s'exécute en local ou en ligne.
330
     */
331
    function is_online(): bool
332
    {
333
        return Helpers::isOnline();
334
    }
335
}
336
337
if (! function_exists('is_connected')) {
338
    /**
339
     * Verifie si l'utilisateur a une connexion internet active.
340
     */
341
    function is_connected(): bool
342
    {
343
        return Helpers::isConnected();
344
    }
345
}
346
347
if (! function_exists('is_ajax_request')) {
348
    /**
349
     * Testez pour voir si une requête contient l'en-tête HTTP_X_REQUESTED_WITH.
350
     */
351
    function is_ajax_request(): bool
352
    {
353
        return Services::request()->is('ajax');
354
    }
355
}
356
357
if (! function_exists('redirection')) {
358
    /**
359
     * Redirige l'utilisateur
360
     */
361
    function redirection(string $uri = '', string $method = 'location', ?int $code = 302)
362
    {
363
        $response = redirect()->to($uri, $code, $method);
364
365
        Services::emitter()->emitHeaders($response);
366
367
        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...
368
    }
369
}
370
371
if (! function_exists('redirect')) {
372
    /**
373
     * Méthode pratique qui fonctionne avec la $request globale actuelle et
374
     * l'instance $router à rediriger à l'aide de routes nommées et le routage inversé
375
     * pour déterminer l'URL à laquelle aller. Si rien n'est trouvé, traitera
376
     * comme une redirection traditionnelle et passez la chaîne, en laissant
377
     * $redirection->redirect() détermine la méthode et le code corrects.
378
     *
379
     * Si plus de contrôle est nécessaire, vous devez utiliser explicitement $response->redirect.
380
     */
381
    function redirect(?string $uri = null): Redirection
382
    {
383
        $redirection = Services::redirection();
384
385
        if (! empty($uri)) {
386
            return $redirection->route($uri);
387
        }
388
389
        return $redirection;
390
    }
391
}
392
393
if (! function_exists('link_to')) {
394
    /**
395
     * Étant donné une chaîne de contrôleur/méthode et tous les paramètres,
396
     * tentera de créer l'URL relative à la route correspondante.
397
     *
398
     * REMARQUE : Cela nécessite que le contrôleur/la méthode
399
     * ait une route définie dans le fichier de configuration des routes.
400
     */
401
    function link_to(string $method, ...$params): string
402
    {
403
        $url = Services::routes()->reverseRoute($method, ...$params);
404
405
        return site_url($url);
406
    }
407
}
408
409
if (! function_exists('clean_path')) {
410
    /**
411
     * Une méthode pratique pour nettoyer les chemins pour
412
     * une sortie plus belle. Utile pour les exceptions
413
     * gestion, journalisation des erreurs, etc.
414
     */
415
    function clean_path(string $path): string
416
    {
417
        $path = realpath($path) ?: $path;
418
419
        switch (true) {
420
            case strpos($path, APP_PATH) === 0:
421
                return 'APP_PATH' . DIRECTORY_SEPARATOR . substr($path, strlen(APP_PATH));
422
423
            case strpos($path, SYST_PATH) === 0:
424
                return 'SYST_PATH' . DIRECTORY_SEPARATOR . substr($path, strlen(SYST_PATH));
425
426
            case defined('VENDOR_PATH') && strpos($path, VENDOR_PATH) === 0:
427
                return 'VENDOR_PATH' . DIRECTORY_SEPARATOR . substr($path, strlen(VENDOR_PATH));
428
429
            case strpos($path, ROOTPATH) === 0:
430
                return 'ROOTPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(ROOTPATH));
431
432
            default:
433
                return $path;
434
        }
435
    }
436
}
437
438
if (! function_exists('old')) {
439
    /**
440
     * Fournit l'accès à "entrée ancienne" qui a été définie dans la session lors d'un redirect()-withInput().
441
     *
442
     * @param false|string $escape
443
     * @phpstan-param false|'attr'|'css'|'html'|'js'|'raw'|'url' $escape
444
     *
445
     * @return array|string|null
446
     */
447
    function old(string $key, ?string $default = null, $escape = 'html')
448
    {
449
        // Assurez-vous de charger la session
450
        if (session_status() === PHP_SESSION_NONE && !on_test()) {
451
            session(); // @codeCoverageIgnore
452
        }
453
454
        // Retourne la valeur par défaut si rien n'a été trouvé dans l'ancien input.
455
        if (null === $value = Services::request()->old($key)) {
456
            return $default;
457
        }
458
459
        return $escape === false ? $value : esc($value, $escape);
460
    }
461
}
462
463
// ================================= FONCTIONS DE DEBOGAGE ================================= //
464
465
if (! function_exists('dd')) {
466
    /**
467
     * Prints a Kint debug report and exits.
468
     *
469
     * @param array ...$vars
470
     *
471
     * @codeCoverageIgnore Can't be tested ... exits
472
     */
473
    function dd(...$vars)
474
    {
475
        if (class_exists('\Kint\Kint')) {
476
            Kint::$aliases[] = 'dd';
477
            Kint::dump(...$vars);
478
        }
479
480
        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...
481
    }
482
}
483
484
if (! function_exists('dump')) {
485
    /**
486
     * Prints a Kint debug report and exits.
487
     *
488
     * @param array ...$vars
489
     *
490
     * @codeCoverageIgnore Can't be tested ... exits
491
     */
492
    function dump(...$vars)
493
    {
494
        if (class_exists('\Kint\Kint')) {
495
            Kint::$aliases[] = 'dump';
496
            Kint::dump(...$vars);
497
        }
498
    }
499
}
500
501
if (! function_exists('deprecationWarning')) {
502
    /**
503
     * Méthode d'assistance pour générer des avertissements d'obsolescence
504
     *
505
     * @param string $message    Le message à afficher comme avertissement d'obsolescence.
506
     * @param int    $stackFrame Le cadre de pile à inclure dans l'erreur. Par défaut à 1
507
     *                           car cela devrait pointer vers le code de l'application/du plugin.
508
     *
509
     * @return void
510
     */
511
    function deprecation_warning(string $message, int $stackFrame = 1)
512
    {
513
        Helpers::deprecationWarning($message, $stackFrame);
514
    }
515
}
516
517
if (! function_exists('logger')) {
518
    /**
519
     * A convenience/compatibility method for logging events through
520
     * the Log system.
521
     *
522
     * Allowed log levels are:
523
     *  - emergency
524
     *  - alert
525
     *  - critical
526
     *  - error
527
     *  - warning
528
     *  - notice
529
     *  - info
530
     *  - debug
531
     *
532
     * @param int|string $level
533
     *
534
     * @return \BlitzPHP\Debug\Logger|mixed
535
     */
536
    function logger($level = null, ?string $message = null, array $context = [])
537
    {
538
        $logger = Services::logger();
539
540
        if (! empty($level) && ! empty($message)) {
541
            return $logger->log($level, $message, $context);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $logger->log($level, $message, $context) targeting BlitzPHP\Debug\Logger::log() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
542
        }
543
544
        return $logger;
545
    }
546
}
547
548
if (! function_exists('cache')) {
549
    /**
550
     * Une méthode pratique qui donne accès au cache
551
     * objet. Si aucun paramètre n'est fourni, renverra l'objet,
552
     * sinon, tentera de renvoyer la valeur mise en cache.
553
     *
554
     * Examples:
555
     *    cache()->set('foo', 'bar'); or cache('foo', 'bar');
556
     *    $foo = cache('bar');
557
     *
558
     * @param mixed|null $value
559
     *
560
     * @return \BlitzPHP\Cache\Cache|bool|mixed
561
     */
562
    function cache(?string $key = null, $value = null)
563
    {
564
        $cache = Services::cache();
565
566
        if (empty($key)) {
567
            return $cache;
568
        }
569
570
        if (empty($value)) {
571
            return $cache->get($key);
572
        }
573
574
        return $cache->set($key, $value);
575
    }
576
}
577
578
if (! function_exists('session')) {
579
    /**
580
     * Une méthode pratique pour accéder à l'instance de session, ou un élément qui a été défini dans la session.
581
     *
582
     * Exemples:
583
     *    session()->set('foo', 'bar');
584
     *    $foo = session('bar');
585
     *
586
     * @return array|bool|float|int|object|Session|string|null
587
     */
588
    function session(?string $val = null)
589
    {
590
        $session = Services::session();
591
592
        // Vous retournez un seul element ?
593
        if (is_string($val)) {
594
            return $session->get($val);
595
        }
596
597
        return $session;
598
    }
599
}
600
601
if (! function_exists('pr')) {
602
    /**
603
     * print_r() convenience function.
604
     *
605
     * In terminals this will act similar to using print_r() directly, when not run on cli
606
     * print_r() will also wrap <pre> tags around the output of given variable. Similar to debug().
607
     *
608
     * This function returns the same variable that was passed.
609
     *
610
     * @param mixed $var Variable to print out.
611
     *
612
     * @return mixed the same $var that was passed to this function
613
     */
614
    function pr($var)
615
    {
616
        $template = (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg') ? '<pre class="pr">%s</pre>' : "\n%s\n\n";
617
        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

617
        printf($template, trim(/** @scrutinizer ignore-type */ print_r($var, true)));
Loading history...
618
619
        return $var;
620
    }
621
}
622
623
if (! function_exists('pj')) {
624
    /**
625
     * json pretty print convenience function.
626
     *
627
     * In terminals this will act similar to using json_encode() with JSON_PRETTY_PRINT directly, when not run on cli
628
     * will also wrap <pre> tags around the output of given variable. Similar to pr().
629
     *
630
     * This function returns the same variable that was passed.
631
     *
632
     * @param mixed $var Variable to print out.
633
     *
634
     * @return mixed the same $var that was passed to this function
635
     *
636
     * @see pr()
637
     */
638
    function pj($var)
639
    {
640
        return Helpers::pj($var);
641
    }
642
}
643
644
if (! function_exists('trigger_warning')) {
645
    /**
646
     * Déclenche un E_USER_WARNING.
647
     */
648
    function trigger_warning(string $message)
649
    {
650
        Helpers::triggerWarning($message);
651
    }
652
}
653
654
if (! function_exists('vd')) {
655
    /**
656
     * Shortcut to ref, HTML mode
657
     *
658
     * @return string|void
659
     */
660
    function vd(...$params)
661
    {
662
        // return 	Helpers::r(...$params);
663
    }
664
}
665
666
if (! function_exists('vdt')) {
667
    /**
668
     * Shortcut to ref, plain text mode
669
     *
670
     * @return string|void
671
     */
672
    function vdt(...$params)
673
    {
674
        // return 	Helpers::rt(...$params);
675
    }
676
}
677
678
// ================================= FONCTIONS DIVERSES ================================= //
679
680
if (! function_exists('force_https')) {
681
    /**
682
     * Utilisé pour forcer l'accès à une page via HTTPS.
683
     * Utilise une redirection standard, plus définira l'en-tête HSTS
684
     * pour les navigateurs modernes qui prennent en charge, ce qui donne une meilleur
685
     * protection contre les attaques de l'homme du milieu.
686
     *
687
     * @see https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security
688
     *
689
     * @param int $duration Combien de temps l'en-tête SSL doit-il être défini ? (en secondes)
690
     *                      Par défaut à 1 an.
691
     *
692
     * @credit CodeIgniter <a href="http://codeigniter.com/">helpers force_https() - /system/Common.php</a>
693
     *
694
     * Non testable, car il sortira !
695
     *
696
     * @codeCoverageIgnore
697
     */
698
    function force_https(int $duration = 31536000, ?ServerRequest $request = null, ?Redirection $response = null)
699
    {
700
        if (null === $request) {
701
            $request = Services::request();
702
        }
703
        if (null === $response) {
704
            $response = Services::redirection();
705
        }
706
707
        if (is_cli() || $request->is('ssl')) {
708
            return;
709
        }
710
711
        // Si la bibliothèque de session est chargée, nous devons régénérer
712
        // l'ID de session pour des raisons de sécurité.
713
        Services::session()->regenerate();
714
715
        $baseURL = base_url();
716
717
        if (strpos($baseURL, 'http://') === 0) {
718
            $baseURL = (string) substr($baseURL, strlen('http://'));
719
        }
720
721
        $uri = Uri::createURIString(
722
            'https',
723
            $baseURL,
724
            $request->getUri()->getPath(), // Les URI absolus doivent utiliser un "/" pour un chemin vide
725
            $request->getUri()->getQuery(),
726
            $request->getUri()->getFragment()
727
        );
728
729
        // Définir un en-tête HSTS
730
        $response = $response->to($uri)->withHeader('Strict-Transport-Security', 'max-age=' . $duration);
731
732
        Services::emitter()->emitHeaders($response);
733
734
        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...
735
    }
736
}
737
738
if (! function_exists('getTypeName')) {
739
    /**
740
     * Renvoie la classe d'objets ou le type var de ce n'est pas un objet
741
     *
742
     * @param mixed $var Variable à vérifier
743
     *
744
     * @return string Renvoie le nom de la classe ou le type de variable
745
     */
746
    function get_type_name($var): string
747
    {
748
        return Helpers::typeName($var);
749
    }
750
}
751
752
if (! function_exists('ip_address')) {
753
    /**
754
     * Renvoie l'adresse IP de l'utilisateur actuel
755
     */
756
    function ip_address(): string
757
    {
758
        return (string) Services::request()->clientIp();
759
    }
760
}
761
762
if (! function_exists('is_really_writable')) {
763
    /**
764
     * Tests d'inscriptibilité des fichiers
765
     */
766
    function is_really_writable(string $file): bool
767
    {
768
        return Helpers::isReallyWritable($file);
769
    }
770
}
771
772
if (! function_exists('lang')) {
773
    /**
774
     * Une méthode pratique pour traduire une chaîne ou un tableau d'entrées et formater
775
     * le résultat avec le MessageFormatter de l'extension intl.
776
     */
777
    function lang(string $line, array $args = [], ?string $locale = null): string
778
    {
779
        return Services::language($locale)->getLine($line, $args);
780
    }
781
}
782
783
if (! function_exists('namespace_split')) {
784
    /**
785
     * Séparez l'espace de noms du nom de classe.
786
     *
787
     * Couramment utilisé comme `list($namespace, $className) = namespaceSplit($class);`.
788
     *
789
     * @param string $class Le nom complet de la classe, ie `BlitzPHP\Http\Request`.
790
     *
791
     * @return array Tableau avec 2 index. 0 => namespace, 1 => classname.
792
     */
793
    function namespace_split(string $class): array
794
    {
795
        $pos = strrpos($class, '\\');
796
        if ($pos === false) {
797
            return ['', $class];
798
        }
799
800
        return [substr($class, 0, $pos), substr($class, $pos + 1)];
801
    }
802
}
803
804
if (! function_exists('view_exist')) {
805
    /**
806
     * Verifie si un fichier de vue existe. Utile pour limiter les failles include
807
     */
808
    function view_exist(string $name, string $ext = '.php'): bool
809
    {
810
        $ext  = str_replace('.', '', $ext);
811
        $name = str_replace(VIEW_PATH, '', $name);
812
        $name = preg_match('#\.' . $ext . '$#', $name) ? $name : $name . '.' . $ext;
813
814
        return is_file(VIEW_PATH . rtrim($name, DS));
815
    }
816
}
817
818
if (! function_exists('view')) {
819
    /**
820
     * Charge une vue
821
     *
822
     * @return \BlitzPHP\View\View
823
     */
824
    function view(string $view, ?array $data = [], ?array $options = [])
825
    {
826
        $object = Services::viewer(false);
827
828
        $object->addData($data)->setOptions($options);
829
830
        return $object->display($view);
831
    }
832
}
833
834
if (! function_exists('flash')) {
835
    /**
836
     * Fournisseur d'acces rapide a la classe PHP Flash
837
     *
838
     * @return FlashMessages|string
839
     */
840
    /*
841
    function flash()
842
    {
843
         @var FlashMessages $flash
844
        $flash = service(FlashMessages::class);
845
846
        $params = func_get_args();
847
        $type = array_shift($params);
848
849
        if (!empty($type)) {
850
            if (empty($params)) {
851
                if ($type === 'all') {
852
                    $type = null;
853
                }
854
                return $flash->display($type, false);
855
            }
856
857
            $message = array_shift($params);
858
859
            return $flash->add($message, $type, ...$params);
860
        }
861
862
        return $flash;
863
    }*/
864
}
865
866
if (! function_exists('geo_ip')) {
867
    /**
868
     * Recuperation des coordonnees (pays, ville, etc) d'un utilisateur en fonction de son ip
869
     */
870
    function geo_ip(?string $ip = null): ?array
871
    {
872
        return json_decode(file_get_contents('http://ip-api.com/json/' . $ip), true);
873
    }
874
}
875
876
if (! function_exists('to_stream')) {
877
    /**
878
     * Créez un nouveau flux basé sur le type d'entrée.
879
     *
880
     * Options est un tableau associatif pouvant contenir les clés suivantes :
881
     * - metadata : Tableau de métadonnées personnalisées.
882
     * - size : Taille du flux.
883
     *
884
     * @param bool|callable|float|int|\Iterator|\Psr\Http\Message\StreamInterface|resource|string|null $resource Données du corps de l'entité
885
     * @param array                                                                                    $options  Additional options
886
     *
887
     * @uses GuzzleHttp\Psr7\stream_for
888
     *
889
     * @return \Psr\Http\Message\StreamInterface
890
     *
891
     * @throws \InvalidArgumentException si l'argument $resource n'est pas valide.
892
     */
893
    function to_stream($resource = '', array $options = []): Psr\Http\Message\StreamInterface
894
    {
895
        return \GuzzleHttp\Psr7\Utils::streamFor($resource, $options);
896
    }
897
}
898
899
if (! function_exists('value')) {
900
    /**
901
     * Renvoie la valeur par défaut de la valeur donnée.
902
     */
903
    function value(mixed $value, ...$args): mixed
904
    {
905
        return Helpers::value($value, ...$args);
906
    }
907
}
908
909
if (! function_exists('collect')) {
910
    /**
911
     * Créez une collection à partir de la valeur donnée.
912
     */
913
    function collect(mixed $value = null): Collection
914
    {
915
        return Helpers::collect($value);
916
    }
917
}
918
919
if (! function_exists('with')) {
920
    /**
921
     * Renvoie la valeur donnée, éventuellement transmise via le rappel donné.
922
     *
923
     * @param mixed $value
924
     */
925
    function with($value, ?callable $callback = null): mixed
926
    {
927
        Helpers::with($value, $callback);
928
    }
929
}
930
931
if (! function_exists('tap')) {
932
    /**
933
     * Appelez la Closure donnée avec cette instance puis renvoyez l'instance.
934
     */
935
    function tap(mixed $value, ?callable $callback = null): mixed
936
    {
937
        return Helpers::tap($value, $callback);
938
    }
939
}
940