Passed
Push — main ( 3399b6...dd4eea )
by Dimitri
11:50
created

FileLocator::helper()   C

Complexity

Conditions 12
Paths 78

Size

Total Lines 69
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 36
c 0
b 0
f 0
nc 78
nop 1
dl 0
loc 69
rs 6.9666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
namespace BlitzPHP\Loader;
13
14
use BlitzPHP\Container\Injector;
15
use BlitzPHP\Container\Services;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, BlitzPHP\Loader\Services. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
16
use BlitzPHP\Contracts\Database\ConnectionInterface;
17
use BlitzPHP\Exceptions\LoadException;
18
use BlitzPHP\Utilities\Helpers;
19
use BlitzPHP\Utilities\String\Text;
20
21
class FileLocator
22
{
23
    /**
24
     * Charge un fichier d'aide en mémoire. 
25
     * Prend en charge les helpers d'espace de noms, à la fois dans et hors du répertoire 'helpers' d'un répertoire d'espace de noms.
26
     *
27
     * Chargera TOUS les helpers du nom correspondant, dans l'ordre suivant :
28
     *   1. app/Helpers
29
     *   2. {namespace}/Helpers
30
     *   3. system/Helpers
31
     *
32
     * @throws FileNotFoundException
33
     */
34
    public static function helper(array|string $filenames)
35
    {
36
        static $loaded = [];
37
38
        $loader = Services::locator();
39
40
        if (! is_array($filenames)) {
0 ignored issues
show
introduced by
The condition is_array($filenames) is always true.
Loading history...
41
            $filenames = [$filenames];
42
        }
43
44
        // Enregistrez une liste de tous les fichiers à inclure...
45
        $includes = [];
46
47
        foreach ($filenames as $filename) {
48
            // Stockez nos versions d'helpers système et d'application afin que nous puissions contrôler l'ordre de chargement.
49
            $systemHelper  = null;
50
            $appHelper     = null;
51
            $localIncludes = [];
52
53
            // Vérifiez si ce helper a déjà été chargé
54
            if (in_array($filename, $loaded, true)) {
55
                continue;
56
            }
57
58
            // Si le fichier est dans un espace de noms, nous allons simplement saisir ce fichier et ne pas en rechercher d'autres
59
            if (strpos($filename, '\\') !== false) {
60
                $path = $loader->locateFile($filename, 'Helpers');
61
62
                if (empty($path)) {
63
                    throw LoadException::helperNotFound($filename);
64
                }
65
66
                $includes[] = $path;
67
                $loaded[]   = $filename;
68
            } else {
69
                // Pas d'espaces de noms, donc recherchez dans tous les emplacements disponibles
70
                $paths = $loader->search('Helpers/' . $filename);
71
72
                foreach ($paths as $path) {
73
                    if (strpos($path, APP_PATH . 'Helpers' . DS) === 0) {
74
                        $appHelper = $path;
75
                    } elseif (strpos($path, SYST_PATH . 'Helpers' . DS) === 0) {
76
                        $systemHelper = $path;
77
                    } else {
78
                        $localIncludes[] = $path;
79
                        $loaded[]        = $filename;
80
                    }
81
                }
82
83
                // Les helpers au niveau de l'application doivent remplacer tous les autres
84
                if (! empty($appHelper)) {
85
                    $includes[] = $appHelper;
86
                    $loaded[]   = $filename;
87
                }
88
89
                // Tous les fichiers avec espace de noms sont ajoutés ensuite
90
                $includes = [...$includes, ...$localIncludes];
91
92
                // Et celui par défaut du système doit être ajouté en dernier.
93
                if (! empty($systemHelper)) {
94
                    $includes[] = $systemHelper;
95
                    $loaded[]   = $filename;
96
                }
97
            }
98
        }
99
100
        // Incluez maintenant tous les fichiers
101
        foreach ($includes as $path) {
102
            include_once $path;
103
        }
104
    }
105
106
    /**
107
     * Cree et renvoie une librairie donnée
108
     *
109
     * @return mixed
110
     */
111
    public static function library(string $library)
112
    {
113
        $library = str_replace(DS, '/', $library);
114
        $library = explode('/', $library);
115
116
        $lib                          = ucfirst(end($library));
117
        $library[count($library) - 1] = $lib;
118
119
        $file  = Helpers::ensureExt(implode(DS, $library), 'php');
120
        $paths = [
121
            SYST_PATH . 'Libraries' . DS . $file,
122
123
            APP_PATH . 'Libraries' . DS . $file,
124
        ];
125
        $file_syst = $file_exist = false;
126
127
        if (file_exists($paths[0])) {
128
            $lib       = "BlitzPhp\\Libraries\\{$lib}";
129
            $file_syst = $file_exist = true;
130
        } elseif (file_exists($paths[1])) {
131
            require_once $paths[1];
132
            $file_exist = true;
133
        }
134
135
        if (true !== $file_exist) {
136
            throw LoadException::libraryNotFound($lib);
137
        }
138
139
        if (true !== $file_syst && ! class_exists($lib)) {
140
            throw LoadException::libraryDontExist($lib);
141
        }
142
143
        return Injector::make($lib);
144
    }
145
146
    /**
147
     * Cree et renvoi un model donné
148
     *
149
     * @template T of \BlitzPHP\Models\BaseModel
150
     *
151
     * @param class-string<T> $model
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<T> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<T>.
Loading history...
152
     *
153
     * @return T
154
     */
155
    public static function model(string $model, ?ConnectionInterface $connection = null)
156
    {
157
        if (! class_exists($model) && ! Text::endsWith($model, 'Model')) {
0 ignored issues
show
Bug introduced by
'Model' of type string is incompatible with the type iterable expected by parameter $needles of BlitzPHP\Utilities\String\Text::endsWith(). ( Ignorable by Annotation )

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

157
        if (! class_exists($model) && ! Text::endsWith($model, /** @scrutinizer ignore-type */ 'Model')) {
Loading history...
158
            $model .= 'Model';
159
        }
160
161
        if (! class_exists($model)) {
162
            $model = str_replace(APP_NAMESPACE . '\\Models\\', '', $model);
163
            $model = APP_NAMESPACE . '\\Models\\' . $model;
164
        }
165
166
        if (! class_exists($model)) {
167
            throw LoadException::modelNotFound($model);
168
        }
169
170
        return Injector::make($model, ['db' => $connection]);
171
    }
172
173
    /**
174
     * Cree et renvoi un controleur donné
175
     *
176
     * @return \dFramework\core\controllers\BaseController
0 ignored issues
show
Bug introduced by
The type dFramework\core\controllers\BaseController 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...
177
     */
178
    public static function controller(string $controller)
179
    {
180
        $controller = str_replace(DS, '/', $controller);
181
        $controller = explode('/', $controller);
182
183
        $con                                = ucfirst(end($controller));
184
        $con                                = (! preg_match('#Controller$#', $con)) ? $con . 'Controller' : $con;
185
        $controller[count($controller) - 1] = $con;
186
187
        foreach ($controller as $key => &$value) {
188
            if (preg_match('#^Controllers?$#i', $value)) {
189
                unset($value, $controller[$key]);
190
            }
191
        }
192
193
        $path = CONTROLLER_PATH . Helpers::ensureExt(implode(DS, $controller), 'php');
194
195
        if (! file_exists($path)) {
196
            throw LoadException::controllerNotFound(str_replace('Controller', '', $con), $path);
197
        }
198
199
        require_once $path;
200
201
        $class_namespaced = implode('\\', $controller);
202
203
        if (class_exists($class_namespaced, false)) {
204
            return Injector::make($class_namespaced);
205
        }
206
        if (! class_exists($con, false)) {
207
            throw LoadException::controllerDontExist(str_replace('Controller', '', $con), $path);
208
        }
209
210
        return Injector::make($con);
211
    }
212
213
    /**
214
     * Recupere le nom de base a partir du nom de la classe, namespacé ou non.
215
     */
216
    public static function getBasename(string $name): string
217
    {
218
        // Determine le basename
219
        if ($basename = strrchr($name, '\\')) {
220
            return substr($basename, 1);
221
        }
222
223
        return $name;
224
    }
225
226
    /**
227
     * Verifie si la classe satisfait l'option "preferApp"
228
     *
229
     * @param array  $options directives specifier pqr le composant
230
     * @param string $name    Nom de la classe, namespace optionel
231
     */
232
    protected static function verifyPreferApp(array $options, string $name): bool
233
    {
234
        // Tout element sans restriction passe
235
        if (! $options['preferApp']) {
236
            return true;
237
        }
238
239
        return strpos($name, APP_NAMESPACE) === 0;
240
    }
241
}
242