Test Setup Failed
Pull Request — 1.1 (#5)
by David
02:18
created

ClassNameMapper   D

Complexity

Total Complexity 59

Size/Duplication

Total Lines 368
Duplicated Lines 25.54 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 59
lcom 1
cbo 1
dl 94
loc 368
rs 4.08
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A registerPsr0Namespace() 19 19 4
A registerPsr4Namespace() 19 19 4
A createFromComposerFile() 0 11 2
A createFromComposerAutoload() 0 12 2
D loadComposerFile() 56 74 19
A loadComposerAutoload() 0 19 4
B makePathRelative() 0 24 7
A getManagedNamespaces() 0 3 1
C getPossibleFileNames() 0 64 10
A unfactorizeAutoload() 0 19 4
A normalizeDirectory() 0 3 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ClassNameMapper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ClassNameMapper, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace Mouf\Composer;
3
4
use function is_readable;
5
6
/**
7
 * The class maps a class name to one or many possible file names according to PSR-0 or PSR-4 rules.
8
 *
9
 * @author David Négrier <[email protected]>
10
 */
11
class ClassNameMapper
12
{
13
    /**
14
     *
15
     * @var array<namespace, path[]>
16
     */
17
    private $psr0Namespaces = array();
18
19
    /**
20
     *
21
     * @var array<namespace, path[]>
22
     */
23
    private $psr4Namespaces = array();
24
25
    /**
26
     * Registers a PSR-0 namespace.
27
     *
28
     * @param string $namespace The namespace to register
29
     * @param string|array $path The path on the filesystem (or an array of paths)
30
     */
31 View Code Duplication
    public function registerPsr0Namespace($namespace, $path) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
32
        // A namespace always ends with a \
33
        $namespace = trim($namespace, '\\').'\\';
34
        if ($namespace === '\\') {
35
            $namespace = '';
36
        }
37
38
        if (!is_array($path)) {
39
            $path = [$path];
40
        }
41
        // Paths always end with a /
42
        $paths = array_map([self::class, 'normalizeDirectory'], $path);
43
44
        if (!isset($this->psr0Namespaces[$namespace])) {
45
            $this->psr0Namespaces[$namespace] = $paths;
46
        } else {
47
            $this->psr0Namespaces[$namespace] = array_merge($this->psr0Namespaces[$namespace], $paths);
48
        }
49
    }
50
51
    /**
52
     * Registers a PSR-4 namespace.
53
     *
54
     * @param string $namespace The namespace to register
55
     * @param string|array $path The path on the filesystem (or an array of paths)
56
     */
57 View Code Duplication
    public function registerPsr4Namespace($namespace, $path) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
58
        // A namespace always ends with a \
59
        $namespace = trim($namespace, '\\').'\\';
60
        if ($namespace === '\\') {
61
            $namespace = '';
62
        }
63
64
        if (!is_array($path)) {
65
            $path = [$path];
66
        }
67
        // Paths always end with a /
68
        $paths = array_map([self::class, 'normalizeDirectory'], $path);
69
70
        if (!isset($this->psr4Namespaces[$namespace])) {
71
            $this->psr4Namespaces[$namespace] = $paths;
72
        } else {
73
            $this->psr4Namespaces[$namespace] = array_merge($this->psr4Namespaces[$namespace], $paths);
74
        }
75
    }
76
77
    /**
78
     * Create a class name mapper from the composer.json file generated by Composer.
79
     * This class name mapper can only map classes in the project directory (not in the vendor directory).
80
     *
81
     * @param string $composerJsonPath
82
     * @param string $rootPath
83
     * @param bool $useAutoloadDev
84
     * @return ClassNameMapper
85
     */
86
    public static function createFromComposerFile($composerJsonPath = null, $rootPath = null, $useAutoloadDev = false) {
87
        $classNameMapper = new ClassNameMapper();
88
89
        if ($composerJsonPath === null) {
90
            $composerJsonPath = __DIR__.'/../../../../composer.json';
91
        }
92
93
        $classNameMapper->loadComposerFile($composerJsonPath, $rootPath, $useAutoloadDev);
94
95
        return $classNameMapper;
96
    }
97
98
    /**
99
     * Create a class name mapper from the autoload.php file generated by Composer.
100
     * This class name mapper can map classes in the project directory AND in the vendor directory.
101
     *
102
     * @param  string|null $composerAutoloadPath
103
     * @return ClassNameMapper
104
     */
105
    public static function createFromComposerAutoload($composerAutoloadPath = null)
106
    {
107
        $classNameMapper = new ClassNameMapper();
108
109
        if ($composerAutoloadPath === null) {
110
            $composerAutoloadPath = __DIR__ . '/../../../autoload.php';
111
        }
112
113
        $classNameMapper->loadComposerAutoload($composerAutoloadPath);
114
115
        return $classNameMapper;
116
    }
117
118
    /**
119
     *
120
     * @param string $composerJsonPath Path to the composer file
121
     * @param string $rootPath Root path of the project (or null)
122
     */
123
    public function loadComposerFile($composerJsonPath, $rootPath = null, $useAutoloadDev = false) {
124
        $composer = json_decode(file_get_contents($composerJsonPath), true);
125
126
        if ($rootPath) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $rootPath of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
127
            $relativePath = self::makePathRelative(dirname($composerJsonPath), $rootPath);
128
        } else {
129
            $relativePath = null;
130
        }
131
132 View Code Duplication
        if (isset($composer["autoload"]["psr-0"])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
133
            $psr0 = $composer["autoload"]["psr-0"];
134
            foreach ($psr0 as $namespace => $paths) {
135
                if ($relativePath != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $relativePath of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
136
                    if (!is_array($paths)) {
137
                        $paths = [$paths];
138
                    }
139
                    $paths = array_map(function($path) use ($relativePath) {
140
                        return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
141
                    }, $paths);
142
                }
143
                $this->registerPsr0Namespace($namespace, $paths);
144
            }
145
        }
146
147 View Code Duplication
        if (isset($composer["autoload"]["psr-4"])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
148
            $psr4 = $composer["autoload"]["psr-4"];
149
150
            foreach ($psr4 as $namespace => $paths) {
151
                if ($relativePath != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $relativePath of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
152
                    if (!is_array($paths)) {
153
                        $paths = [$paths];
154
                    }
155
                    $paths = array_map(function($path) use ($relativePath) {
156
                        return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
157
                    }, $paths);
158
                }
159
                $this->registerPsr4Namespace($namespace, $paths);
160
            }
161
        }
162
163
        if ($useAutoloadDev) {
164 View Code Duplication
            if (isset($composer["autoload-dev"]["psr-0"])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
165
                $psr0 = $composer["autoload-dev"]["psr-0"];
166
                foreach ($psr0 as $namespace => $paths) {
167
                    if ($relativePath != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $relativePath of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
168
                        if (!is_array($paths)) {
169
                            $paths = [$paths];
170
                        }
171
                        $paths = array_map(function($path) use ($relativePath) {
172
                            return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
173
                        }, $paths);
174
                    }
175
                    $this->registerPsr0Namespace($namespace, $paths);
176
                }
177
            }
178
179 View Code Duplication
            if (isset($composer["autoload-dev"]["psr-4"])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
180
                $psr4 = $composer["autoload-dev"]["psr-4"];
181
                foreach ($psr4 as $namespace => $paths) {
182
                    if ($relativePath != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $relativePath of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
183
                        if (!is_array($paths)) {
184
                            $paths = [$paths];
185
                        }
186
                        $paths = array_map(function($path) use ($relativePath) {
187
                            return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
188
                        }, $paths);
189
                    }
190
                    $this->registerPsr4Namespace($namespace, $paths);
191
                }
192
            }
193
        }
194
195
        return $this;
196
    }
197
198
    /**
199
     * @param  string $composerAutoloadPath
200
     * @return self
201
     */
202
    public function loadComposerAutoload($composerAutoloadPath)
203
    {
204
        if (!is_readable($composerAutoloadPath)) {
205
            throw MissingFileException::couldNotLoadFile($composerAutoloadPath);
206
        }
207
208
        $loader = require $composerAutoloadPath;
209
210
        foreach ($loader->getPrefixes() as $namespace => $paths) {
211
            $this->registerPsr0Namespace($namespace, $paths);
212
        }
213
214
        foreach ($loader->getPrefixesPsr4() as $namespace => $paths) {
215
            $this->registerPsr4Namespace($namespace, $paths);
216
        }
217
218
219
        return $this;
220
    }
221
222
    /**
223
     * Given an existing path, convert it to a path relative to a given starting path.
224
     * Shamelessly borrowed to Symfony :). Thanks guys.
225
     * Note: we do not include Symfony's "FileSystem" component to avoid adding too many dependencies.
226
     *
227
     * @param string $endPath Absolute path of target
228
     * @param string $startPath Absolute path where traversal begins
229
     *
230
     * @return string Path of target relative to starting path
231
     */
232
    private static function makePathRelative($endPath, $startPath)
233
    {
234
        // Normalize separators on Windows
235
        if ('\\' === DIRECTORY_SEPARATOR) {
236
            $endPath = strtr($endPath, '\\', '/');
237
            $startPath = strtr($startPath, '\\', '/');
238
        }
239
        // Split the paths into arrays
240
        $startPathArr = explode('/', trim($startPath, '/'));
241
        $endPathArr = explode('/', trim($endPath, '/'));
242
        // Find for which directory the common path stops
243
        $index = 0;
244
        while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
245
            $index++;
246
        }
247
        // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
248
        $depth = count($startPathArr) - $index;
249
        // Repeated "../" for each level need to reach the common path
250
        $traverser = str_repeat('../', $depth);
251
        $endPathRemainder = implode('/', array_slice($endPathArr, $index));
252
        // Construct $endPath from traversing to the common path, then to the remaining $endPath
253
        $relativePath = $traverser.(strlen($endPathRemainder) > 0 ? $endPathRemainder.'/' : '');
254
        return (strlen($relativePath) === 0) ? './' : $relativePath;
255
    }
256
257
    /**
258
     * Returns a list of all namespaces that are managed by the ClassNameMapper.
259
     *
260
     * @return string[]
261
     */
262
    public function getManagedNamespaces() {
263
        return array_keys(array_merge($this->psr0Namespaces, $this->psr4Namespaces));
264
    }
265
266
    /**
267
     * Returns a list of paths that can be used to store $className.
268
     *
269
     * @param string $className
270
     * @return string[]
271
     */
272
    public function getPossibleFileNames($className) {
273
        $possibleFileNames = array();
274
        $className = ltrim($className, '\\');
275
276
        $psr0unfactorizedAutoload = $this->unfactorizeAutoload($this->psr0Namespaces);
277
278
        foreach ($psr0unfactorizedAutoload as $result) {
279
            $namespace = $result['namespace'];
280
            $directory = $result['directory'];
281
282
            if ($namespace === '') {
283
                $tmpClassName = $className;
284
                if ($lastNsPos = strripos($tmpClassName, '\\')) {
285
                    $namespace = substr($tmpClassName, 0, $lastNsPos);
286
                    $tmpClassName = substr($tmpClassName, $lastNsPos + 1);
287
                }
288
289
                $fileName = str_replace('\\', '/', $namespace) . '/' . str_replace('_', '/', $tmpClassName) . '.php';
290
                $possibleFileNames[] = $directory.$fileName;
291
            } else {
292
                if (strpos($className, $namespace) === 0) {
293
                    $tmpClassName = $className;
294
                    $fileName  = '';
295
                    if ($lastNsPos = strripos($tmpClassName, '\\')) {
296
                        $namespace = substr($tmpClassName, 0, $lastNsPos);
297
                        $tmpClassName = substr($tmpClassName, $lastNsPos + 1);
298
                        $fileName  = str_replace('\\', '/', $namespace) . '/';
299
                    }
300
                    $fileName .= str_replace('_', '/', $tmpClassName) . '.php';
301
302
                    $possibleFileNames[] = $directory.$fileName;
303
                }
304
            }
305
        }
306
307
        $psr4unfactorizedAutoload = $this->unfactorizeAutoload($this->psr4Namespaces);
308
309
        foreach ($psr4unfactorizedAutoload as $result) {
310
            $namespace = $result['namespace'];
311
            $directory = $result['directory'];
312
313
            if ($namespace === '') {
314
                $fileName = str_replace('\\', '/', $className) . '.php';
315
                $possibleFileNames[] = $directory.$fileName;
316
            } else {
317
                if (strpos($className, $namespace) === 0) {
318
                    $shortenedClassName = substr($className, strlen($namespace));
319
320
                    if ($lastNsPos = strripos($shortenedClassName, '\\')) {
321
                        $namespace = substr($shortenedClassName, 0, $lastNsPos);
322
                        $shortenedClassName = substr($shortenedClassName, $lastNsPos + 1);
323
                        $fileName = str_replace('\\', '/', $namespace) . '/' . $shortenedClassName;
324
                    } else {
325
                        $fileName = $shortenedClassName;
326
                    }
327
                    $fileName .= '.php';
328
329
                    $possibleFileNames[] = $directory . $fileName;
330
                }
331
            }
332
        }
333
334
        return $possibleFileNames;
335
    }
336
337
    /**
338
     * Takes in parameter an array like
339
     * [{ "Mouf": "src/" }] or [{ "Mouf": ["src/", "src2/"] }] .
340
     * returns
341
     * [
342
     * 	{"namespace"=> "Mouf", "directory"=>"src/"},
343
     * 	{"namespace"=> "Mouf", "directory"=>"src2/"}
344
     * ]
345
     *
346
     * @param array $autoload
347
     * @return array<int, array<string, string>>
0 ignored issues
show
Documentation introduced by
The doc-type array<int, could not be parsed: Expected ">" at position 5, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
348
     */
349
    private static function unfactorizeAutoload(array $autoload) {
350
        $result  = array();
351
        foreach ($autoload as $namespace => $directories) {
352
            if (!is_array($directories)) {
353
                $result[] = array(
354
                    "namespace" => $namespace,
355
                    "directory" => self::normalizeDirectory($directories)
356
                );
357
            } else {
358
                foreach ($directories as $dir) {
359
                    $result[] = array(
360
                        "namespace" => $namespace,
361
                        "directory" => self::normalizeDirectory($dir)
362
                    );
363
                }
364
            }
365
        }
366
        return $result;
367
    }
368
369
    /**
370
     * Makes sure the directory ends with a / (unless the string is empty)
371
     *
372
     * @param string $dir
373
     * @return string
374
     */
375
    private static function normalizeDirectory($dir) {
376
        return $dir === '' ? '' : rtrim($dir, '\\/').'/';
377
    }
378
}
379