Passed
Pull Request — 1.0 (#4)
by
unknown
02:07
created

ClassNameMapper   D

Complexity

Total Complexity 59

Size/Duplication

Total Lines 359
Duplicated Lines 26.18 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 59
lcom 1
cbo 0
dl 94
loc 359
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 16 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
/**
5
 * The class maps a class name to one or many possible file names according to PSR-0 or PSR-4 rules.
6
 *
7
 * @author David Négrier <[email protected]>
8
 */
9
class ClassNameMapper
10
{
11
    /**
12
     *
13
     * @var array<namespace, path[]>
14
     */
15
    private $psr0Namespaces = array();
16
17
    /**
18
     *
19
     * @var array<namespace, path[]>
20
     */
21
    private $psr4Namespaces = array();
22
23
    /**
24
     * Registers a PSR-0 namespace.
25
     *
26
     * @param string $namespace The namespace to register
27
     * @param string|array $path The path on the filesystem (or an array of paths)
28
     */
29 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...
30
        // A namespace always ends with a \
31
        $namespace = trim($namespace, '\\').'\\';
32
        if ($namespace === '\\') {
33
            $namespace = '';
34
        }
35
36
        if (!is_array($path)) {
37
            $path = [$path];
38
        }
39
        // Paths always end with a /
40
        $paths = array_map([self::class, 'normalizeDirectory'], $path);
41
42
        if (!isset($this->psr0Namespaces[$namespace])) {
43
            $this->psr0Namespaces[$namespace] = $paths;
44
        } else {
45
            $this->psr0Namespaces[$namespace] = array_merge($this->psr0Namespaces[$namespace], $paths);
46
        }
47
    }
48
49
    /**
50
     * Registers a PSR-4 namespace.
51
     *
52
     * @param string $namespace The namespace to register
53
     * @param string|array $path The path on the filesystem (or an array of paths)
54
     */
55 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...
56
        // A namespace always ends with a \
57
        $namespace = trim($namespace, '\\').'\\';
58
        if ($namespace === '\\') {
59
            $namespace = '';
60
        }
61
62
        if (!is_array($path)) {
63
            $path = [$path];
64
        }
65
        // Paths always end with a /
66
        $paths = array_map([self::class, 'normalizeDirectory'], $path);
67
68
        if (!isset($this->psr4Namespaces[$namespace])) {
69
            $this->psr4Namespaces[$namespace] = $paths;
70
        } else {
71
            $this->psr4Namespaces[$namespace] = array_merge($this->psr4Namespaces[$namespace], $paths);
72
        }
73
    }
74
75
    /**
76
     * @param string $composerJsonPath
77
     * @param string $rootPath
78
     * @param bool $useAutoloadDev
79
     * @return ClassNameMapper
80
     */
81
    public static function createFromComposerFile($composerJsonPath = null, $rootPath = null, $useAutoloadDev = false) {
82
        $classNameMapper = new ClassNameMapper();
83
84
        if ($composerJsonPath === null) {
85
            $composerJsonPath = __DIR__.'/../../../../composer.json';
86
        }
87
88
        $classNameMapper->loadComposerFile($composerJsonPath, $rootPath, $useAutoloadDev);
89
90
        return $classNameMapper;
91
    }
92
93
    /**
94
     * @param  string|null $composerAutoloadPath
95
     * @return ClassNameMapper
96
     */
97
    public static function createFromComposerAutoload($composerAutoloadPath = null)
98
    {
99
        $classNameMapper = new ClassNameMapper();
100
101
        if ($composerAutoloadPath === null) {
102
            $composerAutoloadPath = __DIR__ . '/../../../autoload.php';
103
        }
104
105
        $classNameMapper->loadComposerAutoload($composerAutoloadPath);
106
107
        return $classNameMapper;
108
    }
109
110
    /**
111
     *
112
     * @param string $composerJsonPath Path to the composer file
113
     * @param string $rootPath Root path of the project (or null)
114
     */
115
    public function loadComposerFile($composerJsonPath, $rootPath = null, $useAutoloadDev = false) {
116
        $composer = json_decode(file_get_contents($composerJsonPath), true);
117
118
        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...
119
            $relativePath = self::makePathRelative(dirname($composerJsonPath), $rootPath);
120
        } else {
121
            $relativePath = null;
122
        }
123
124 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...
125
            $psr0 = $composer["autoload"]["psr-0"];
126
            foreach ($psr0 as $namespace => $paths) {
127
                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...
128
                    if (!is_array($paths)) {
129
                        $paths = [$paths];
130
                    }
131
                    $paths = array_map(function($path) use ($relativePath) {
132
                        return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
133
                    }, $paths);
134
                }
135
                $this->registerPsr0Namespace($namespace, $paths);
136
            }
137
        }
138
139 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...
140
            $psr4 = $composer["autoload"]["psr-4"];
141
142
            foreach ($psr4 as $namespace => $paths) {
143
                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...
144
                    if (!is_array($paths)) {
145
                        $paths = [$paths];
146
                    }
147
                    $paths = array_map(function($path) use ($relativePath) {
148
                        return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
149
                    }, $paths);
150
                }
151
                $this->registerPsr4Namespace($namespace, $paths);
152
            }
153
        }
154
155
        if ($useAutoloadDev) {
156 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...
157
                $psr0 = $composer["autoload-dev"]["psr-0"];
158
                foreach ($psr0 as $namespace => $paths) {
159
                    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...
160
                        if (!is_array($paths)) {
161
                            $paths = [$paths];
162
                        }
163
                        $paths = array_map(function($path) use ($relativePath) {
164
                            return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
165
                        }, $paths);
166
                    }
167
                    $this->registerPsr0Namespace($namespace, $paths);
168
                }
169
            }
170
171 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...
172
                $psr4 = $composer["autoload-dev"]["psr-4"];
173
                foreach ($psr4 as $namespace => $paths) {
174
                    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...
175
                        if (!is_array($paths)) {
176
                            $paths = [$paths];
177
                        }
178
                        $paths = array_map(function($path) use ($relativePath) {
179
                            return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
180
                        }, $paths);
181
                    }
182
                    $this->registerPsr4Namespace($namespace, $paths);
183
                }
184
            }
185
        }
186
187
        return $this;
188
    }
189
190
    /**
191
     * @param  string $composerAutoloadPath
192
     * @return self
193
     */
194
    public function loadComposerAutoload($composerAutoloadPath)
195
    {
196
        if (file_exists($composerAutoloadPath)) {
197
            $loader = require $composerAutoloadPath;
198
199
            foreach ($loader->getPrefixes() as $namespace => $paths) {
200
                $this->registerPsr0Namespace($namespace, $paths);
201
            }
202
203
            foreach ($loader->getPrefixesPsr4() as $namespace => $paths) {
204
                $this->registerPsr4Namespace($namespace, $paths);
205
            }
206
        }
207
208
        return $this;
209
    }
210
211
    /**
212
     * Given an existing path, convert it to a path relative to a given starting path.
213
     * Shamelessly borrowed to Symfony :). Thanks guys.
214
     * Note: we do not include Symfony's "FileSystem" component to avoid adding too many dependencies.
215
     *
216
     * @param string $endPath Absolute path of target
217
     * @param string $startPath Absolute path where traversal begins
218
     *
219
     * @return string Path of target relative to starting path
220
     */
221
    private static function makePathRelative($endPath, $startPath)
222
    {
223
        // Normalize separators on Windows
224
        if ('\\' === DIRECTORY_SEPARATOR) {
225
            $endPath = strtr($endPath, '\\', '/');
226
            $startPath = strtr($startPath, '\\', '/');
227
        }
228
        // Split the paths into arrays
229
        $startPathArr = explode('/', trim($startPath, '/'));
230
        $endPathArr = explode('/', trim($endPath, '/'));
231
        // Find for which directory the common path stops
232
        $index = 0;
233
        while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
234
            $index++;
235
        }
236
        // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
237
        $depth = count($startPathArr) - $index;
238
        // Repeated "../" for each level need to reach the common path
239
        $traverser = str_repeat('../', $depth);
240
        $endPathRemainder = implode('/', array_slice($endPathArr, $index));
241
        // Construct $endPath from traversing to the common path, then to the remaining $endPath
242
        $relativePath = $traverser.(strlen($endPathRemainder) > 0 ? $endPathRemainder.'/' : '');
243
        return (strlen($relativePath) === 0) ? './' : $relativePath;
244
    }
245
246
    /**
247
     * Returns a list of all namespaces that are managed by the ClassNameMapper.
248
     *
249
     * @return string[]
250
     */
251
    public function getManagedNamespaces() {
252
        return array_keys(array_merge($this->psr0Namespaces, $this->psr4Namespaces));
253
    }
254
255
    /**
256
     * Returns a list of paths that can be used to store $className.
257
     *
258
     * @param string $className
259
     * @return string[]
260
     */
261
    public function getPossibleFileNames($className) {
262
        $possibleFileNames = array();
263
        $className = ltrim($className, '\\');
264
265
        $psr0unfactorizedAutoload = $this->unfactorizeAutoload($this->psr0Namespaces);
266
267
        foreach ($psr0unfactorizedAutoload as $result) {
268
            $namespace = $result['namespace'];
269
            $directory = $result['directory'];
270
271
            if ($namespace === '') {
272
                $tmpClassName = $className;
273
                if ($lastNsPos = strripos($tmpClassName, '\\')) {
274
                    $namespace = substr($tmpClassName, 0, $lastNsPos);
275
                    $tmpClassName = substr($tmpClassName, $lastNsPos + 1);
276
                }
277
278
                $fileName = str_replace('\\', '/', $namespace) . '/' . str_replace('_', '/', $tmpClassName) . '.php';
279
                $possibleFileNames[] = $directory.$fileName;
280
            } else {
281
                if (strpos($className, $namespace) === 0) {
282
                    $tmpClassName = $className;
283
                    $fileName  = '';
284
                    if ($lastNsPos = strripos($tmpClassName, '\\')) {
285
                        $namespace = substr($tmpClassName, 0, $lastNsPos);
286
                        $tmpClassName = substr($tmpClassName, $lastNsPos + 1);
287
                        $fileName  = str_replace('\\', '/', $namespace) . '/';
288
                    }
289
                    $fileName .= str_replace('_', '/', $tmpClassName) . '.php';
290
291
                    $possibleFileNames[] = $directory.$fileName;
292
                }
293
            }
294
        }
295
296
        $psr4unfactorizedAutoload = $this->unfactorizeAutoload($this->psr4Namespaces);
297
298
        foreach ($psr4unfactorizedAutoload as $result) {
299
            $namespace = $result['namespace'];
300
            $directory = $result['directory'];
301
302
            if ($namespace === '') {
303
                $fileName = str_replace('\\', '/', $className) . '.php';
304
                $possibleFileNames[] = $directory.$fileName;
305
            } else {
306
                if (strpos($className, $namespace) === 0) {
307
                    $shortenedClassName = substr($className, strlen($namespace));
308
309
                    if ($lastNsPos = strripos($shortenedClassName, '\\')) {
310
                        $namespace = substr($shortenedClassName, 0, $lastNsPos);
311
                        $shortenedClassName = substr($shortenedClassName, $lastNsPos + 1);
312
                        $fileName = str_replace('\\', '/', $namespace) . '/' . $shortenedClassName;
313
                    } else {
314
                        $fileName = $shortenedClassName;
315
                    }
316
                    $fileName .= '.php';
317
318
                    $possibleFileNames[] = $directory . $fileName;
319
                }
320
            }
321
        }
322
323
        return $possibleFileNames;
324
    }
325
326
    /**
327
     * Takes in parameter an array like
328
     * [{ "Mouf": "src/" }] or [{ "Mouf": ["src/", "src2/"] }] .
329
     * returns
330
     * [
331
     * 	{"namespace"=> "Mouf", "directory"=>"src/"},
332
     * 	{"namespace"=> "Mouf", "directory"=>"src2/"}
333
     * ]
334
     *
335
     * @param array $autoload
336
     * @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...
337
     */
338
    private static function unfactorizeAutoload(array $autoload) {
339
        $result  = array();
340
        foreach ($autoload as $namespace => $directories) {
341
            if (!is_array($directories)) {
342
                $result[] = array(
343
                    "namespace" => $namespace,
344
                    "directory" => self::normalizeDirectory($directories)
345
                );
346
            } else {
347
                foreach ($directories as $dir) {
348
                    $result[] = array(
349
                        "namespace" => $namespace,
350
                        "directory" => self::normalizeDirectory($dir)
351
                    );
352
                }
353
            }
354
        }
355
        return $result;
356
    }
357
358
    /**
359
     * Makes sure the directory ends with a / (unless the string is empty)
360
     *
361
     * @param string $dir
362
     * @return string
363
     */
364
    private static function normalizeDirectory($dir) {
365
        return $dir === '' ? '' : rtrim($dir, '\\/').'/';
366
    }
367
}
368