Passed
Push — main ( 633b92...66245a )
by Dimitri
12:27
created

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

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