Passed
Push — main ( aa68b0...40dc38 )
by Dimitri
03:05
created

session()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 10
rs 10
1
<?php
2
3
/**
4
 * This file is part of Blitz PHP framework.
5
 *
6
 * (c) 2022 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
use BlitzPHP\Config\Config;
13
use BlitzPHP\Contracts\Database\ConnectionInterface;
14
use BlitzPHP\Exceptions\PageNotFoundException;
15
use BlitzPHP\Http\Redirection;
16
use BlitzPHP\Http\ServerRequest;
17
use BlitzPHP\Http\Uri;
18
use BlitzPHP\Loader\Load;
19
use BlitzPHP\Loader\Services;
20
use BlitzPHP\Session\Session;
21
use BlitzPHP\Utilities\Helpers;
22
use BlitzPHP\Utilities\Iterable\Collection;
23
use Kint\Kint;
24
25
// ================================= FONCTIONS D'ACCESSIBILITE ================================= //
26
27
if (! function_exists('env')) {
28
    /**
29
     * Obtient une variable d'environnement à partir des sources disponibles et fournit une émulation
30
     * pour les variables d'environnement non prises en charge ou incohérentes
31
     *
32
     * @param string     $key     Nom de la variable d'environnement
33
     * @param mixed|null $default
34
     *
35
     * @return string Paramétrage des variables d'environnement.
36
     */
37
    function env(string $key, $default = null)
38
    {
39
        return Helpers::env($key, $default);
40
    }
41
}
42
43
if (! function_exists('helper')) {
44
    /**
45
     * Charge un fichier d'aide en mémoire. Prend en charge les assistants d'espace de noms,
46
     * à la fois dans et hors du répertoire 'helpers' d'un répertoire à espace de noms.
47
     *
48
     * Chargera TOUS les assistants du nom correspondant, dans l'ordre suivant :
49
     *   1. app/Helpers
50
     *   2. {namespace}/Helpers
51
     *   3. system/Helpers
52
     *
53
     * @param array|string $filenames
54
     */
55
    function helper($filenames)
56
    {
57
        Load::helper($filenames);
58
    }
59
}
60
61
if (! function_exists('model')) {
62
    /**
63
     * Simple maniere d'obtenir un modele.
64
     *
65
     * @template T of BlitzPHP\Models\BaseModel
66
     *
67
     * @param array<class-string<T>>|class-string<T> $name
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<class-string<T>>|class-string<T> at position 2 could not be parsed: Unknown type name 'class-string' at position 2 in array<class-string<T>>|class-string<T>.
Loading history...
68
     *
69
     * @return T
70
     */
71
    function model(string|array $name, array $options = [], ?ConnectionInterface &$conn = null)
72
    {
73
        return Load::model($name, $options, $conn);
0 ignored issues
show
Bug Best Practice introduced by
The expression return BlitzPHP\Loader\L...$name, $options, $conn) also could return the type array<mixed,object> which is incompatible with the documented return type T.
Loading history...
74
    }
75
}
76
77
if (! function_exists('service')) {
78
    /**
79
     * Permet un accès plus propre au fichier de configuration des services.
80
     * Renvoie toujours une instance SHARED de la classe, donc
81
     * appeler la fonction plusieurs fois doit toujours
82
     * renvoie la même instance.
83
     *
84
     * Ceux-ci sont égaux :
85
     *  - $cache = service('cache')
86
     *  - $cache = \BlitzPHP\Loader\Services::cache();
87
     */
88
    function service(string $name, ...$params)
89
    {
90
        return Services::$name(...$params);
91
    }
92
}
93
94
if (! function_exists('single_service')) {
95
    /**
96
     * Autoriser l'accès propre à un service.
97
     * Renvoie toujours une nouvelle instance de la classe.
98
     */
99
    function single_service(string $name, ...$params)
100
    {
101
        // Assurez-vous qu'il ne s'agit PAS d'une instance partagée
102
        $params[] = false;
103
104
        return Services::$name(...$params);
105
    }
106
}
107
108
if (! function_exists('show404')) {
109
    /**
110
     * Afficher une page 404 introuvable dans le navigateur
111
     */
112
    function show404(string $message = 'The page you requested was not found.', string $heading = 'Page Not Found', array $params = [])
113
    {
114
        throw PageNotFoundException::pageNotFound($message);
115
    }
116
}
117
118
if (! function_exists('config')) {
119
    /**
120
     * GET/SET App config
121
     *
122
     * @param mixed $value
123
     *
124
     * @return mixed
125
     */
126
    function config(string $config, $value = null, bool $force_set = false)
127
    {
128
        if (! empty($value) || (empty($value) && true === $force_set)) {
129
            Config::set($config, $value);
130
        }
131
132
        return Config::get($config);
133
    }
134
}
135
136
// =========================== FONCTIONS DE PREVENTION D'ATTAQUE =========================== //
137
138
if (! function_exists('esc')) {
139
    /**
140
     * Effectue un simple échappement automatique des données pour des raisons de sécurité.
141
     * Pourrait envisager de rendre cela plus complexe à une date ultérieure.
142
     *
143
     * Si $data est une chaîne, il suffit alors de l'échapper et de la renvoyer.
144
     * Si $data est un tableau, alors il boucle dessus, s'échappant de chaque
145
     * 'valeur' des paires clé/valeur.
146
     *
147
     * Valeurs de contexte valides : html, js, css, url, attr, raw, null
148
     *
149
     * @param array|string $data
150
     *
151
     * @return array|string
152
     *
153
     * @throws InvalidArgumentException
154
     */
155
    function esc($data, ?string $context = 'html', ?string $encoding = null)
156
    {
157
        if (class_exists('\Laminas\Escaper\Escaper')) {
158
            return Helpers::esc($data, $context, $encoding);
159
        }
160
161
        return h($data, true, $encoding);
162
    }
163
}
164
165
if (! function_exists('h')) {
166
    /**
167
     * Méthode pratique pour htmlspecialchars.
168
     *
169
     * @param mixed       $text    Texte à envelopper dans htmlspecialchars. Fonctionne également avec des tableaux et des objets.
170
     *                             Les tableaux seront mappés et tous leurs éléments seront échappés. Les objets seront transtypés s'ils
171
     *                             implémenter une méthode `__toString`. Sinon, le nom de la classe sera utilisé.
172
     *                             Les autres types de scalaires seront renvoyés tels quels.
173
     * @param bool        $double  Encodez les entités html existantes.
174
     * @param string|null $charset Jeu de caractères à utiliser lors de l'échappement. La valeur par défaut est la valeur de configuration dans `mb_internal_encoding()` ou 'UTF-8'.
175
     *
176
     * @return mixed Texte enveloppé.
177
     */
178
    function h($text, bool $double = true, ?string $charset = null)
179
    {
180
        return Helpers::h($text, $double, $charset);
181
    }
182
}
183
184
if (! function_exists('purify')) {
185
    /**
186
     * Purifiez l'entrée à l'aide de la classe autonome HTMLPurifier.
187
     * Utilisez facilement plusieurs configurations de purificateur.
188
     *
189
     * @param string|string[]
190
     * @param false|string
191
     * @param mixed $dirty_html
192
     * @param mixed $config
193
     *
194
     * @return string|string[]
195
     */
196
    function purify($dirty_html, $config = false)
197
    {
198
        return Helpers::purify($dirty_html, $config);
199
    }
200
}
201
202
if (! function_exists('remove_invisible_characters')) {
203
    /**
204
     * Supprimer les caractères invisibles
205
     *
206
     * Cela empêche de prendre en sandwich des caractères nuls
207
     * entre les caractères ascii, comme Java\0script.
208
     */
209
    function remove_invisible_characters(string $str, bool $url_encoded = true): string
210
    {
211
        return Helpers::removeInvisibleCharacters($str, $url_encoded);
212
    }
213
}
214
215
if (! function_exists('stringify_attributes')) {
216
    /**
217
     * Chaîner les attributs à utiliser dans les balises HTML.
218
     *
219
     * @param array|object|string $attributes
220
     */
221
    function stringify_attributes($attributes, bool $js = false): string
222
    {
223
        return Helpers::stringifyAttributes($attributes, $js);
224
    }
225
}
226
227
// ================================= FONCTIONS D'ENVIRONNEMENT D'EXECUTION ================================= //
228
229
if (! function_exists('on_dev')) {
230
    /**
231
     * Testez pour voir si nous sommes dans un environnement de développement.
232
     */
233
    function on_dev(bool $checkOnline = false): bool
234
    {
235
        if ($checkOnline && is_online()) {
236
            return false;
237
        }
238
239
        $env = config('app.environment');
240
241
        return in_array($env, ['dev', 'development'], true);
242
    }
243
}
244
245
if (! function_exists('on_prod')) {
246
    /**
247
     * Testez pour voir si nous sommes dans un environnement de production.
248
     */
249
    function on_prod(bool $checkOnline = false): bool
250
    {
251
        if ($checkOnline && is_online()) {
252
            return true;
253
        }
254
255
        $env = config('app.environment');
256
257
        return in_array($env, ['prod', 'production'], true);
258
    }
259
}
260
261
if (! function_exists('on_test')) {
262
    /**
263
     * Testez pour voir si nous sommes dans un environnement de test
264
     */
265
    function on_test(): bool
266
    {
267
        $env = config('app.environment');
268
269
        return in_array($env, ['test', 'testing'], true);
270
    }
271
}
272
273
if (! function_exists('is_cli')) {
274
    /**
275
     * Testez pour voir si une demande a été faite à partir de la ligne de commande.
276
     */
277
    function is_cli(): bool
278
    {
279
        return Helpers::isCli();
280
    }
281
}
282
283
if (! function_exists('is_php')) {
284
    /**
285
     * Détermine si la version actuelle de PHP est égale ou supérieure à la valeur fournie.
286
     */
287
    function is_php(string $version): bool
288
    {
289
        return Helpers::isPhp($version);
290
    }
291
}
292
293
if (! function_exists('is_windows')) {
294
    /**
295
     * Déterminez si l'environnement actuel est basé sur Windows.
296
     */
297
    function is_windows(): bool
298
    {
299
        return PHP_OS_FAMILY === 'Windows';
300
    }
301
}
302
303
if (! function_exists('is_https')) {
304
    /**
305
     * Determines if the application is accessed via an encrypted * (HTTPS) connection.
306
     */
307
    function is_https(): bool
308
    {
309
        return Services::request()->is('ssl');
310
    }
311
}
312
313
if (! function_exists('is_localfile')) {
314
    /**
315
     * Vérifiez si le fichier auquel vous souhaitez accéder est un fichier local de votre application ou non
316
     */
317
    function is_localfile(string $name): bool
318
    {
319
        if (preg_match('#^' . base_url() . '#i', $name)) {
320
            return true;
321
        }
322
323
        return ! preg_match('#^(https?://)#i', $name);
324
    }
325
}
326
327
if (! function_exists('is_online')) {
328
    /**
329
     * Tester si l'application s'exécute en local ou en ligne.
330
     */
331
    function is_online(): bool
332
    {
333
        return Helpers::isOnline();
334
    }
335
}
336
337
if (! function_exists('is_connected')) {
338
    /**
339
     * Verifie si l'utilisateur a une connexion internet active.
340
     */
341
    function is_connected(): bool
342
    {
343
        return Helpers::isConnected();
344
    }
345
}
346
347
if (! function_exists('is_ajax_request')) {
348
    /**
349
     * Testez pour voir si une requête contient l'en-tête HTTP_X_REQUESTED_WITH.
350
     */
351
    function is_ajax_request(): bool
352
    {
353
        return Services::request()->is('ajax');
354
    }
355
}
356
357
if (! function_exists('redirection')) {
358
    /**
359
     * Redirige l'utilisateur
360
     */
361
    function redirection(string $uri = '', string $method = 'location', ?int $code = 302)
362
    {
363
        $response = redirect()->to($uri, $code, $method);
364
365
        Services::emitter()->emitHeaders($response);
366
367
        exit(EXIT_SUCCESS);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
368
    }
369
}
370
371
if (! function_exists('redirect')) {
372
    /**
373
     * Méthode pratique qui fonctionne avec la $request globale actuelle et
374
     * l'instance $router à rediriger à l'aide de routes nommées et le routage inversé
375
     * pour déterminer l'URL à laquelle aller. Si rien n'est trouvé, traitera
376
     * comme une redirection traditionnelle et passez la chaîne, en laissant
377
     * $redirection->redirect() détermine la méthode et le code corrects.
378
     *
379
     * Si plus de contrôle est nécessaire, vous devez utiliser explicitement $response->redirect.
380
     */
381
    function redirect(?string $uri = null): Redirection
382
    {
383
        $redirection = Services::redirection();
384
385
        if (! empty($uri)) {
386
            return $redirection->route($uri);
387
        }
388
389
        return $redirection;
390
    }
391
}
392
393
if (! function_exists('link_to')) {
394
    /**
395
     * Étant donné une chaîne de contrôleur/méthode et tous les paramètres,
396
     * tentera de créer l'URL relative à la route correspondante.
397
     *
398
     * REMARQUE : Cela nécessite que le contrôleur/la méthode
399
     * ait une route définie dans le fichier de configuration des routes.
400
     */
401
    function link_to(string $method, ...$params): string
402
    {
403
        $url = Services::routes()->reverseRoute($method, ...$params);
404
405
        return site_url($url);
406
    }
407
}
408
409
if (! function_exists('clean_path')) {
410
    /**
411
     * Une méthode pratique pour nettoyer les chemins pour
412
     * une sortie plus belle. Utile pour les exceptions
413
     * gestion, journalisation des erreurs, etc.
414
     */
415
    function clean_path(string $path): string
416
    {
417
        $path = realpath($path) ?: $path;
418
419
        switch (true) {
420
            case strpos($path, APP_PATH) === 0:
421
                return 'APP_PATH' . DIRECTORY_SEPARATOR . substr($path, strlen(APP_PATH));
422
423
            case strpos($path, SYST_PATH) === 0:
424
                return 'SYST_PATH' . DIRECTORY_SEPARATOR . substr($path, strlen(SYST_PATH));
425
426
            case defined('VENDOR_PATH') && strpos($path, VENDOR_PATH) === 0:
427
                return 'VENDOR_PATH' . DIRECTORY_SEPARATOR . substr($path, strlen(VENDOR_PATH));
428
429
            case strpos($path, ROOTPATH) === 0:
430
                return 'ROOTPATH' . DIRECTORY_SEPARATOR . substr($path, strlen(ROOTPATH));
431
432
            default:
433
                return $path;
434
        }
435
    }
436
}
437
438
// ================================= FONCTIONS DE DEBOGAGE ================================= //
439
440
if (! function_exists('dd')) {
441
    /**
442
     * Prints a Kint debug report and exits.
443
     *
444
     * @param array ...$vars
445
     *
446
     * @codeCoverageIgnore Can't be tested ... exits
447
     */
448
    function dd(...$vars)
449
    {
450
        if (class_exists('\Kint\Kint')) {
451
            Kint::$aliases[] = 'dd';
452
            Kint::dump(...$vars);
453
        }
454
455
        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...
456
    }
457
}
458
459
if (! function_exists('dump')) {
460
    /**
461
     * Prints a Kint debug report and exits.
462
     *
463
     * @param array ...$vars
464
     *
465
     * @codeCoverageIgnore Can't be tested ... exits
466
     */
467
    function dump(...$vars)
468
    {
469
        if (class_exists('\Kint\Kint')) {
470
            Kint::$aliases[] = 'dump';
471
            Kint::dump(...$vars);
472
        }
473
    }
474
}
475
476
if (! function_exists('deprecationWarning')) {
477
    /**
478
     * Méthode d'assistance pour générer des avertissements d'obsolescence
479
     *
480
     * @param string $message    Le message à afficher comme avertissement d'obsolescence.
481
     * @param int    $stackFrame Le cadre de pile à inclure dans l'erreur. Par défaut à 1
482
     *                           car cela devrait pointer vers le code de l'application/du plugin.
483
     *
484
     * @return void
485
     */
486
    function deprecation_warning(string $message, int $stackFrame = 1)
487
    {
488
        Helpers::deprecationWarning($message, $stackFrame);
489
    }
490
}
491
492
if (! function_exists('logger')) {
493
    /**
494
     * A convenience/compatibility method for logging events through
495
     * the Log system.
496
     *
497
     * Allowed log levels are:
498
     *  - emergency
499
     *  - alert
500
     *  - critical
501
     *  - error
502
     *  - warning
503
     *  - notice
504
     *  - info
505
     *  - debug
506
     *
507
     * @param int|string $level
508
     *
509
     * @return \BlitzPHP\Debug\Logger|mixed
510
     */
511
    function logger($level = null, ?string $message = null, array $context = [])
512
    {
513
        $logger = Services::logger();
514
515
        if (! empty($level) && ! empty($message)) {
516
            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...
517
        }
518
519
        return $logger;
520
    }
521
}
522
523
if (! function_exists('cache')) {
524
    /**
525
     * Une méthode pratique qui donne accès au cache
526
     * objet. Si aucun paramètre n'est fourni, renverra l'objet,
527
     * sinon, tentera de renvoyer la valeur mise en cache.
528
     *
529
     * Examples:
530
     *    cache()->set('foo', 'bar'); or cache('foo', 'bar');
531
     *    $foo = cache('bar');
532
     *
533
     * @param mixed|null $value
534
     *
535
     * @return \BlitzPHP\Cache\Cache|bool|mixed
536
     */
537
    function cache(?string $key = null, $value = null)
538
    {
539
        $cache = Services::cache();
540
541
        if (empty($key)) {
542
            return $cache;
543
        }
544
545
        if (empty($value)) {
546
            return $cache->get($key);
547
        }
548
549
        return $cache->set($key, $value);
550
    }
551
}
552
553
if (! function_exists('session')) {
554
    /**
555
     * Une méthode pratique pour accéder à l'instance de session, ou un élément qui a été défini dans la session.
556
     *
557
     * Exemples:
558
     *    session()->set('foo', 'bar');
559
     *    $foo = session('bar');
560
     *
561
     * @return array|bool|float|int|object|Session|string|null
562
     */
563
    function session(?string $val = null)
564
    {
565
        $session = Services::session();
566
567
        // Vous retournez un seul element ?
568
        if (is_string($val)) {
569
            return $session->get($val);
570
        }
571
572
        return $session;
573
    }
574
}
575
576
if (! function_exists('pr')) {
577
    /**
578
     * print_r() convenience function.
579
     *
580
     * In terminals this will act similar to using print_r() directly, when not run on cli
581
     * print_r() will also wrap <pre> tags around the output of given variable. Similar to debug().
582
     *
583
     * This function returns the same variable that was passed.
584
     *
585
     * @param mixed $var Variable to print out.
586
     *
587
     * @return mixed the same $var that was passed to this function
588
     */
589
    function pr($var)
590
    {
591
        $template = (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg') ? '<pre class="pr">%s</pre>' : "\n%s\n\n";
592
        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

592
        printf($template, trim(/** @scrutinizer ignore-type */ print_r($var, true)));
Loading history...
593
594
        return $var;
595
    }
596
}
597
598
if (! function_exists('pj')) {
599
    /**
600
     * json pretty print convenience function.
601
     *
602
     * In terminals this will act similar to using json_encode() with JSON_PRETTY_PRINT directly, when not run on cli
603
     * will also wrap <pre> tags around the output of given variable. Similar to pr().
604
     *
605
     * This function returns the same variable that was passed.
606
     *
607
     * @param mixed $var Variable to print out.
608
     *
609
     * @return mixed the same $var that was passed to this function
610
     *
611
     * @see pr()
612
     */
613
    function pj($var)
614
    {
615
        return Helpers::pj($var);
616
    }
617
}
618
619
if (! function_exists('trigger_warning')) {
620
    /**
621
     * Déclenche un E_USER_WARNING.
622
     */
623
    function trigger_warning(string $message)
624
    {
625
        Helpers::triggerWarning($message);
626
    }
627
}
628
629
if (! function_exists('vd')) {
630
    /**
631
     * Shortcut to ref, HTML mode
632
     *
633
     * @return string|void
634
     */
635
    function vd(...$params)
636
    {
637
        // return 	Helpers::r(...$params);
638
    }
639
}
640
641
if (! function_exists('vdt')) {
642
    /**
643
     * Shortcut to ref, plain text mode
644
     *
645
     * @return string|void
646
     */
647
    function vdt(...$params)
648
    {
649
        // return 	Helpers::rt(...$params);
650
    }
651
}
652
653
// ================================= FONCTIONS DIVERSES ================================= //
654
655
if (! function_exists('force_https')) {
656
    /**
657
     * Utilisé pour forcer l'accès à une page via HTTPS.
658
     * Utilise une redirection standard, plus définira l'en-tête HSTS
659
     * pour les navigateurs modernes qui prennent en charge, ce qui donne une meilleur
660
     * protection contre les attaques de l'homme du milieu.
661
     *
662
     * @see https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security
663
     *
664
     * @param int $duration Combien de temps l'en-tête SSL doit-il être défini ? (en secondes)
665
     *                      Par défaut à 1 an.
666
     *
667
     * @credit CodeIgniter <a href="http://codeigniter.com/">helpers force_https() - /system/Common.php</a>
668
     *
669
     * Non testable, car il sortira !
670
     *
671
     * @codeCoverageIgnore
672
     */
673
    function force_https(int $duration = 31536000, ?ServerRequest $request = null, ?Redirection $response = null)
674
    {
675
        if (null === $request) {
676
            $request = Services::request();
677
        }
678
        if (null === $response) {
679
            $response = Services::redirection();
680
        }
681
682
        if (is_cli() || $request->is('ssl')) {
683
            return;
684
        }
685
686
        // Si la bibliothèque de session est chargée, nous devons régénérer
687
        // l'ID de session pour des raisons de sécurité.
688
        Services::session()->renew();
0 ignored issues
show
Bug introduced by
The method renew() does not exist on BlitzPHP\Session\Session. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

688
        Services::session()->/** @scrutinizer ignore-call */ renew();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
689
690
        $baseURL = base_url();
691
692
        if (strpos($baseURL, 'http://') === 0) {
693
            $baseURL = (string) substr($baseURL, strlen('http://'));
694
        }
695
696
        $uri = Uri::createURIString(
697
            'https',
698
            $baseURL,
699
            $request->getUri()->getPath(), // Les URI absolus doivent utiliser un "/" pour un chemin vide
700
            $request->getUri()->getQuery(),
701
            $request->getUri()->getFragment()
702
        );
703
704
        // Définir un en-tête HSTS
705
        $response = $response->to($uri)->withHeader('Strict-Transport-Security', 'max-age=' . $duration);
706
707
        Services::emitter()->emitHeaders($response);
708
709
        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...
710
    }
711
}
712
713
if (! function_exists('getTypeName')) {
714
    /**
715
     * Renvoie la classe d'objets ou le type var de ce n'est pas un objet
716
     *
717
     * @param mixed $var Variable à vérifier
718
     *
719
     * @return string Renvoie le nom de la classe ou le type de variable
720
     */
721
    function get_type_name($var): string
722
    {
723
        return Helpers::typeName($var);
724
    }
725
}
726
727
if (! function_exists('ip_address')) {
728
    /**
729
     * Renvoie l'adresse IP de l'utilisateur actuel
730
     */
731
    function ip_address(): string
732
    {
733
        return (string) Services::request()->clientIp();
734
    }
735
}
736
737
if (! function_exists('is_really_writable')) {
738
    /**
739
     * Tests d'inscriptibilité des fichiers
740
     */
741
    function is_really_writable(string $file): bool
742
    {
743
        return Helpers::isReallyWritable($file);
744
    }
745
}
746
747
if (! function_exists('lang')) {
748
    /**
749
     * Une méthode pratique pour traduire une chaîne ou un tableau d'entrées et formater
750
     * le résultat avec le MessageFormatter de l'extension intl.
751
     */
752
    function lang(string $line, array $args = [], ?string $locale = null): string
753
    {
754
        return Services::language($locale)->getLine($line, $args);
755
    }
756
}
757
758
if (! function_exists('namespace_split')) {
759
    /**
760
     * Séparez l'espace de noms du nom de classe.
761
     *
762
     * Couramment utilisé comme `list($namespace, $className) = namespaceSplit($class);`.
763
     *
764
     * @param string $class Le nom complet de la classe, ie `BlitzPHP\Http\Request`.
765
     *
766
     * @return array Tableau avec 2 index. 0 => namespace, 1 => classname.
767
     */
768
    function namespace_split(string $class): array
769
    {
770
        $pos = strrpos($class, '\\');
771
        if ($pos === false) {
772
            return ['', $class];
773
        }
774
775
        return [substr($class, 0, $pos), substr($class, $pos + 1)];
776
    }
777
}
778
779
if (! function_exists('view_exist')) {
780
    /**
781
     * Verifie si un fichier de vue existe. Utile pour limiter les failles include
782
     */
783
    function view_exist(string $name, string $ext = '.php'): bool
784
    {
785
        $ext  = str_replace('.', '', $ext);
786
        $name = str_replace(VIEW_PATH, '', $name);
787
        $name = preg_match('#\.' . $ext . '$#', $name) ? $name : $name . '.' . $ext;
788
789
        return is_file(VIEW_PATH . rtrim($name, DS));
790
    }
791
}
792
793
if (! function_exists('view')) {
794
    /**
795
     * Charge une vue
796
     *
797
     * @return \BlitzPHP\View\View
798
     */
799
    function view(string $view, ?array $data = [], ?array $options = [])
800
    {
801
        $object = Services::viewer(false);
802
803
        $object->addData($data)->setOptions($options);
804
805
        return $object->display($view);
806
    }
807
}
808
809
if (! function_exists('flash')) {
810
    /**
811
     * Fournisseur d'acces rapide a la classe PHP Flash
812
     *
813
     * @return FlashMessages|string
814
     */
815
    /*
816
    function flash()
817
    {
818
         @var FlashMessages $flash
819
        $flash = service(FlashMessages::class);
820
821
        $params = func_get_args();
822
        $type = array_shift($params);
823
824
        if (!empty($type)) {
825
            if (empty($params)) {
826
                if ($type === 'all') {
827
                    $type = null;
828
                }
829
                return $flash->display($type, false);
830
            }
831
832
            $message = array_shift($params);
833
834
            return $flash->add($message, $type, ...$params);
835
        }
836
837
        return $flash;
838
    }*/
839
}
840
841
if (! function_exists('geo_ip')) {
842
    /**
843
     * Recuperation des coordonnees (pays, ville, etc) d'un utilisateur en fonction de son ip
844
     */
845
    function geo_ip(?string $ip = null): ?array
846
    {
847
        return json_decode(file_get_contents('http://ip-api.com/json/' . $ip), true);
848
    }
849
}
850
851
if (! function_exists('to_stream')) {
852
    /**
853
     * Créez un nouveau flux basé sur le type d'entrée.
854
     *
855
     * Options est un tableau associatif pouvant contenir les clés suivantes :
856
     * - metadata : Tableau de métadonnées personnalisées.
857
     * - size : Taille du flux.
858
     *
859
     * @param bool|callable|float|int|\Iterator|\Psr\Http\Message\StreamInterface|resource|string|null $resource Données du corps de l'entité
860
     * @param array                                                                                    $options  Additional options
861
     *
862
     * @uses GuzzleHttp\Psr7\stream_for
863
     *
864
     * @return \Psr\Http\Message\StreamInterface
865
     *
866
     * @throws \InvalidArgumentException si l'argument $resource n'est pas valide.
867
     */
868
    function to_stream($resource = '', array $options = []): Psr\Http\Message\StreamInterface
869
    {
870
        return \GuzzleHttp\Psr7\Utils::streamFor($resource, $options);
871
    }
872
}
873
874
if (! function_exists('value')) {
875
    /**
876
     * Renvoie la valeur par défaut de la valeur donnée.
877
     */
878
    function value(mixed $value, ...$args): mixed
879
    {
880
        return Helpers::value($value, ...$args);
881
    }
882
}
883
884
if (! function_exists('collect')) {
885
    /**
886
     * Créez une collection à partir de la valeur donnée.
887
     */
888
    function collect(mixed $value = null): Collection
889
    {
890
        return Helpers::collect($value);
891
    }
892
}
893
894
if (! function_exists('with')) {
895
    /**
896
     * Renvoie la valeur donnée, éventuellement transmise via le rappel donné.
897
     *
898
     * @param mixed $value
899
     */
900
    function with($value, ?callable $callback = null): mixed
901
    {
902
        Helpers::with($value, $callback);
903
    }
904
}
905
906
if (! function_exists('tap')) {
907
    /**
908
     * Appelez la Closure donnée avec cette instance puis renvoyez l'instance.
909
     */
910
    function tap(mixed $value, ?callable $callback = null): mixed
911
    {
912
        return Helpers::tap($value, $callback);
913
    }
914
}
915