Passed
Push — main ( 2e91a7...db810f )
by Dimitri
03:15
created

invade()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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

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