Passed
Push — main ( 172c86...5eb528 )
by Dimitri
03:20
created

__()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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

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