Passed
Push — main ( 097cc9...20cf55 )
by Dimitri
03:38
created

vdt()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

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

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