Passed
Push — main ( ebe3be...5a020f )
by Dimitri
22:02 queued 12s
created

is_connected()   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 0
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\Database\Contracts\ConnectionInterface;
0 ignored issues
show
Bug introduced by
The type BlitzPHP\Database\Contracts\ConnectionInterface 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...
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\Utilities\Helpers;
21
use Kint\Kint;
22
23
// ================================= FONCTIONS D'ACCESSIBILITE ================================= //
24
25
if (! function_exists('env')) {
26
    /**
27
     * Obtient une variable d'environnement à partir des sources disponibles et fournit une émulation
28
     * pour les variables d'environnement non prises en charge ou incohérentes
29
     *
30
     * @param string     $key     Nom de la variable d'environnement
31
     * @param mixed|null $default
32
     *
33
     * @return string Paramétrage des variables d'environnement.
34
     */
35
    function env(string $key, $default = null)
36
    {
37
        return Helpers::env($key, $default);
38
    }
39
}
40
41
if (! function_exists('helper')) {
42
    /**
43
     * Charge un fichier d'aide en mémoire. Prend en charge les assistants d'espace de noms,
44
     * à la fois dans et hors du répertoire 'helpers' d'un répertoire à espace de noms.
45
     *
46
     * Chargera TOUS les assistants du nom correspondant, dans l'ordre suivant :
47
     *   1. app/Helpers
48
     *   2. {namespace}/Helpers
49
     *   3. system/Helpers
50
     *
51
     * @param array|string $filenames
52
     */
53
    function helper($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, array $options = [], ?ConnectionInterface &$conn = null)
70
    {
71
        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...
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
     * @param mixed $value
121
     *
122
     * @return mixed
123
     */
124
    function config(string $config, $value = null, bool $force_set = false)
125
    {
126
        if (! empty($value) || (empty($value) && true === $force_set)) {
127
            Config::set($config, $value);
128
        }
129
130
        return Config::get($config);
131
    }
132
}
133
134
// =========================== FONCTIONS DE PREVENTION D'ATTAQUE =========================== //
135
136
if (! function_exists('esc')) {
137
    /**
138
     * Effectue un simple échappement automatique des données pour des raisons de sécurité.
139
     * Pourrait envisager de rendre cela plus complexe à une date ultérieure.
140
     *
141
     * Si $data est une chaîne, il suffit alors de l'échapper et de la renvoyer.
142
     * Si $data est un tableau, alors il boucle dessus, s'échappant de chaque
143
     * 'valeur' des paires clé/valeur.
144
     *
145
     * Valeurs de contexte valides : html, js, css, url, attr, raw, null
146
     *
147
     * @param array|string $data
148
     *
149
     * @throws InvalidArgumentException
150
     *
151
     * @return array|string
152
     */
153
    function esc($data, ?string $context = 'html', ?string $encoding = null)
154
    {
155
        if (class_exists('\Laminas\Escaper\Escaper')) {
156
            return Helpers::esc($data, $context, $encoding);
157
        }
158
159
        return h($data, true, $encoding);
160
    }
161
}
162
163
if (! function_exists('h')) {
164
    /**
165
     * Méthode pratique pour htmlspecialchars.
166
     *
167
     * @param mixed       $text    Texte à envelopper dans htmlspecialchars. Fonctionne également avec des tableaux et des objets.
168
     *                             Les tableaux seront mappés et tous leurs éléments seront échappés. Les objets seront transtypés s'ils
169
     *                             implémenter une méthode `__toString`. Sinon, le nom de la classe sera utilisé.
170
     *                             Les autres types de scalaires seront renvoyés tels quels.
171
     * @param bool        $double  Encodez les entités html existantes.
172
     * @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'.
173
     *
174
     * @return mixed Texte enveloppé.
175
     */
176
    function h($text, bool $double = true, ?string $charset = null)
177
    {
178
        return Helpers::h($text, $double, $charset);
179
    }
180
}
181
182
if (! function_exists('purify')) {
183
    /**
184
     * Purifiez l'entrée à l'aide de la classe autonome HTMLPurifier.
185
     * Utilisez facilement plusieurs configurations de purificateur.
186
     *
187
     * @param string|string[]
188
     * @param false|string
189
     * @param mixed $dirty_html
190
     * @param mixed $config
191
     *
192
     * @return string|string[]
193
     */
194
    function purify($dirty_html, $config = false)
195
    {
196
        return Helpers::purify($dirty_html, $config);
197
    }
198
}
199
200
if (! function_exists('remove_invisible_characters')) {
201
    /**
202
     * Supprimer les caractères invisibles
203
     *
204
     * Cela empêche de prendre en sandwich des caractères nuls
205
     * entre les caractères ascii, comme Java\0script.
206
     */
207
    function remove_invisible_characters(string $str, bool $url_encoded = true): string
208
    {
209
        return Helpers::removeInvisibleCharacters($str, $url_encoded);
210
    }
211
}
212
213
if (! function_exists('stringify_attributes')) {
214
    /**
215
     * Chaîner les attributs à utiliser dans les balises HTML.
216
     *
217
     * @param array|object|string $attributes
218
     */
219
    function stringify_attributes($attributes, bool $js = false): string
220
    {
221
        return Helpers::stringifyAttributes($attributes, $js);
222
    }
223
}
224
225
// ================================= FONCTIONS D'ENVIRONNEMENT D'EXECUTION ================================= //
226
227
if (! function_exists('on_dev')) {
228
    /**
229
     * Testez pour voir si nous sommes dans un environnement de développement.
230
     */
231
    function on_dev(bool $checkOnline = false): bool
232
    {
233
        if ($checkOnline && is_online()) {
234
            return false;
235
        }
236
237
        $env = config('app.environment');
238
239
        return in_array($env, ['dev', 'development'], true);
240
    }
241
}
242
243
if (! function_exists('on_prod')) {
244
    /**
245
     * Testez pour voir si nous sommes dans un environnement de production.
246
     */
247
    function on_prod(bool $checkOnline = false): bool
248
    {
249
        if ($checkOnline && is_online()) {
250
            return true;
251
        }
252
253
        $env = config('app.environment');
254
255
        return in_array($env, ['prod', 'production'], true);
256
    }
257
}
258
259
if (! function_exists('on_test')) {
260
    /**
261
     * Testez pour voir si nous sommes dans un environnement de test
262
     */
263
    function on_test(): bool
264
    {
265
        $env = config('app.environment');
266
267
        return in_array($env, ['test', 'testing'], true);
268
    }
269
}
270
271
if (! function_exists('is_cli')) {
272
    /**
273
     * Testez pour voir si une demande a été faite à partir de la ligne de commande.
274
     */
275
    function is_cli(): bool
276
    {
277
        return PHP_SAPI === 'cli' || defined('STDIN');
278
    }
279
}
280
281
if (! function_exists('is_php')) {
282
    /**
283
     * Détermine si la version actuelle de PHP est égale ou supérieure à la valeur fournie.
284
     */
285
    function is_php(string $version): bool
286
    {
287
        return Helpers::isPhp($version);
288
    }
289
}
290
291
if (! function_exists('is_windows')) {
292
    /**
293
     * Déterminez si l'environnement actuel est basé sur Windows.
294
     */
295
    function is_windows(): bool
296
    {
297
        return PHP_OS_FAMILY === 'Windows';
298
    }
299
}
300
301
if (! function_exists('is_https')) {
302
    /**
303
     * Determines if the application is accessed via an encrypted * (HTTPS) connection.
304
     */
305
    function is_https(): bool
306
    {
307
        return Services::request()->is('ssl');
308
    }
309
}
310
311
if (! function_exists('is_localfile')) {
312
    /**
313
     * Vérifiez si le fichier auquel vous souhaitez accéder est un fichier local de votre application ou non
314
     */
315
    function is_localfile(string $name): bool
316
    {
317
        if (preg_match('#^' . base_url() . '#i', $name)) {
318
            return true;
319
        }
320
321
        return ! preg_match('#^(https?://)#i', $name);
322
    }
323
}
324
325
if (! function_exists('is_online')) {
326
    /**
327
     * Tester si l'application s'exécute en local ou en ligne.
328
     */
329
    function is_online(): bool
330
    {
331
        return Helpers::isOnline();
332
    }
333
}
334
335
if (! function_exists('is_connected')) {
336
    /**
337
     * Verifie si l'utilisateur a une connexion internet active.
338
     */
339
    function is_connected(): bool
340
    {
341
        return Helpers::isConnected();
0 ignored issues
show
Bug introduced by
The method isConnected() does not exist on BlitzPHP\Utilities\Helpers. ( Ignorable by Annotation )

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

341
        return Helpers::/** @scrutinizer ignore-call */ isConnected();

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

567
        printf($template, trim(/** @scrutinizer ignore-type */ print_r($var, true)));
Loading history...
568
569
        return $var;
570
    }
571
}
572
573
if (! function_exists('pj')) {
574
    /**
575
     * json pretty print convenience function.
576
     *
577
     * In terminals this will act similar to using json_encode() with JSON_PRETTY_PRINT directly, when not run on cli
578
     * will also wrap <pre> tags around the output of given variable. Similar to pr().
579
     *
580
     * This function returns the same variable that was passed.
581
     *
582
     * @param mixed $var Variable to print out.
583
     *
584
     * @return mixed the same $var that was passed to this function
585
     *
586
     * @see pr()
587
     */
588
    function pj($var)
589
    {
590
        return Helpers::pj($var);
591
    }
592
}
593
594
if (! function_exists('trigger_warning')) {
595
    /**
596
     * Déclenche un E_USER_WARNING.
597
     */
598
    function trigger_warning(string $message)
599
    {
600
        Helpers::triggerWarning($message);
601
    }
602
}
603
604
if (! function_exists('vd')) {
605
    /**
606
     * Shortcut to ref, HTML mode
607
     *
608
     * @return string|void
609
     */
610
    function vd(...$params)
611
    {
612
        // return 	Helpers::r(...$params);
613
    }
614
}
615
616
if (! function_exists('vdt')) {
617
    /**
618
     * Shortcut to ref, plain text mode
619
     *
620
     * @return string|void
621
     */
622
    function vdt(...$params)
623
    {
624
        // return 	Helpers::rt(...$params);
625
    }
626
}
627
628
// ================================= FONCTIONS DIVERSES ================================= //
629
630
if (! function_exists('force_https')) {
631
    /**
632
     * Utilisé pour forcer l'accès à une page via HTTPS.
633
     * Utilise une redirection standard, plus définira l'en-tête HSTS
634
     * pour les navigateurs modernes qui prennent en charge, ce qui donne une meilleur
635
     * protection contre les attaques de l'homme du milieu.
636
     *
637
     * @see https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security
638
     *
639
     * @param int $duration Combien de temps l'en-tête SSL doit-il être défini ? (en secondes)
640
     *                      Par défaut à 1 an.
641
     *
642
     * @credit CodeIgniter <a href="http://codeigniter.com/">helpers force_https() - /system/Common.php</a>
643
     *
644
     * Non testable, car il sortira !
645
     *
646
     * @codeCoverageIgnore
647
     */
648
    function force_https(int $duration = 31536000, ?ServerRequest $request = null, ?Redirection $response = null)
649
    {
650
        if (null === $request) {
651
            $request = Services::request();
652
        }
653
        if (null === $response) {
654
            $response = Services::redirection();
655
        }
656
657
        if (is_cli() || $request->is('ssl')) {
658
            return;
659
        }
660
661
        // Si la bibliothèque de session est chargée, nous devons régénérer
662
        // l'ID de session pour des raisons de sécurité.
663
        Services::session()->renew();
664
665
        $baseURL = base_url();
666
667
        if (strpos($baseURL, 'http://') === 0) {
668
            $baseURL = (string) substr($baseURL, strlen('http://'));
669
        }
670
671
        $uri = Uri::createURIString(
672
            'https',
673
            $baseURL,
674
            $request->getUri()->getPath(), // Les URI absolus doivent utiliser un "/" pour un chemin vide
675
            $request->getUri()->getQuery(),
676
            $request->getUri()->getFragment()
677
        );
678
679
        // Définir un en-tête HSTS
680
        $response = $response->to($uri)->withHeader('Strict-Transport-Security', 'max-age=' . $duration);
681
682
        Services::emitter()->emitHeaders($response);
683
684
        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...
685
    }
686
}
687
688
if (! function_exists('getTypeName')) {
689
    /**
690
     * Renvoie la classe d'objets ou le type var de ce n'est pas un objet
691
     *
692
     * @param mixed $var Variable à vérifier
693
     *
694
     * @return string Renvoie le nom de la classe ou le type de variable
695
     */
696
    function get_type_name($var): string
697
    {
698
        return is_object($var) ? get_class($var) : gettype($var);
699
    }
700
}
701
702
if (! function_exists('ip_address')) {
703
    /**
704
     * Renvoie l'adresse IP de l'utilisateur actuel
705
     */
706
    function ip_address(): string
707
    {
708
        return (string) Services::request()->clientIp();
709
    }
710
}
711
712
if (! function_exists('is_really_writable')) {
713
    /**
714
     * Tests d'inscriptibilité des fichiers
715
     */
716
    function is_really_writable(string $file): bool
717
    {
718
        return true;
719
        // return Helpers::is_really_writable($file);
720
    }
721
}
722
723
if (! function_exists('lang')) {
724
    /**
725
     * Une méthode pratique pour traduire une chaîne ou un tableau d'entrées et formater
726
     * le résultat avec le MessageFormatter de l'extension intl.
727
     *
728
     * @param array  $args
729
     * @param string $locale
730
     *
731
     * @return string
732
     */
733
    function lang(string $line, ?array $args = [], ?string $locale = null)
734
    {
735
        return Services::language($locale)->getLine($line, $args);
0 ignored issues
show
Bug Best Practice introduced by
The expression return BlitzPHP\Loader\S...->getLine($line, $args) also could return the type string[] which is incompatible with the documented return type string.
Loading history...
736
    }
737
}
738
739
if (! function_exists('namespaceSplit')) {
740
    /**
741
     * Séparez l'espace de noms du nom de classe.
742
     *
743
     * Couramment utilisé comme `list($namespace, $className) = namespaceSplit($class);`.
744
     *
745
     * @param string $class Le nom complet de la classe, ie `BlitzPHP\Http\Request`.
746
     *
747
     * @return array Tableau avec 2 index. 0 => namespace, 1 => classname.
748
     */
749
    function namespace_split(string $class): array
750
    {
751
        $pos = strrpos($class, '\\');
752
        if ($pos === false) {
753
            return ['', $class];
754
        }
755
756
        return [substr($class, 0, $pos), substr($class, $pos + 1)];
757
    }
758
}
759
760
if (! function_exists('view_exist')) {
761
    /**
762
     * Verifie si un fichier de vue existe. Utile pour limiter les failles include
763
     */
764
    function view_exist(string $name, string $ext = '.php'): bool
765
    {
766
        $ext  = str_replace('.', '', $ext);
767
        $name = str_replace(VIEW_PATH, '', $name);
768
        $name = preg_match('#\.' . $ext . '$#', $name) ? $name : $name . '.' . $ext;
769
770
        return is_file(VIEW_PATH . rtrim($name, DS));
771
    }
772
}
773
774
if (! function_exists('view')) {
775
    /**
776
     * Charge une vue
777
     *
778
     * @return \BlitzPHP\View\View
779
     */
780
    function view(string $view, ?array $data = [], ?array $options = [])
781
    {
782
        $object = Services::viewer(false);
783
784
        $object->addData($data)->setOptions($options);
785
786
        return $object->display($view);
787
    }
788
}
789
790
if (! function_exists('flash')) {
791
    /**
792
     * Fournisseur d'acces rapide a la classe PHP Flash
793
     *
794
     * @return FlashMessages|string
795
     */
796
    /*
797
    function flash()
798
    {
799
         @var FlashMessages $flash
800
        $flash = service(FlashMessages::class);
801
802
        $params = func_get_args();
803
        $type = array_shift($params);
804
805
        if (!empty($type)) {
806
            if (empty($params)) {
807
                if ($type === 'all') {
808
                    $type = null;
809
                }
810
                return $flash->display($type, false);
811
            }
812
813
            $message = array_shift($params);
814
815
            return $flash->add($message, $type, ...$params);
816
        }
817
818
        return $flash;
819
    }*/
820
}
821
822
if (! function_exists('geo_ip')) {
823
    /**
824
     * Recuperation des coordonnees (pays, ville, etc) d'un utilisateur en fonction de son ip
825
     */
826
    function geo_ip(?string $ip = null): ?array
827
    {
828
        return json_decode(file_get_contents('http://ip-api.com/json/' . $ip), true);
829
    }
830
}
831
832
if (! function_exists('to_stream')) {
833
    /**
834
     * Créez un nouveau flux basé sur le type d'entrée.
835
     *
836
     * Options est un tableau associatif pouvant contenir les clés suivantes :
837
     * - metadata : Tableau de métadonnées personnalisées.
838
     * - size : Taille du flux.
839
     *
840
     * @param bool|callable|float|int|\Iterator|\Psr\Http\Message\StreamInterface|resource|string|null $resource Données du corps de l'entité
841
     * @param array                                                                                    $options  Additional options
842
     *
843
     * @uses GuzzleHttp\Psr7\stream_for
844
     *
845
     * @throws \InvalidArgumentException si l'argument $resource n'est pas valide.
846
     *
847
     * @return \Psr\Http\Message\StreamInterface
848
     */
849
    function to_stream($resource = '', array $options = []): Psr\Http\Message\StreamInterface
850
    {
851
        return \GuzzleHttp\Psr7\Utils::streamFor($resource, $options);
852
    }
853
}
854
855
if (! function_exists('value')) {
856
    /**
857
     * Renvoie la valeur par défaut de la valeur donnée.
858
     *
859
     * @param mixed $value
860
     *
861
     * @return mixed
862
     */
863
    function value($value)
864
    {
865
        return $value instanceof Closure ? $value() : $value;
866
    }
867
}
868
869
if (! function_exists('with')) {
870
    /**
871
     * Renvoie la valeur donnée, éventuellement transmise via le rappel donné.
872
     *
873
     * @param mixed $value
874
     *
875
     * @return mixed
876
     */
877
    function with($value, ?callable $callback = null)
878
    {
879
        return null === $callback ? $value : $callback($value);
880
    }
881
}
882