Passed
Push — main ( 02442c...4ee80d )
by Dimitri
13:27
created

back()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 3
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\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;
0 ignored issues
show
Bug introduced by
The type BlitzPHP\Session\Store was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

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

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