Passed
Pull Request — 1.0 (#3)
by David
02:13
created

ClassNameMapper   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 314
Duplicated Lines 31.21 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 55
lcom 1
cbo 0
dl 98
loc 314
rs 6
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A createFromComposerFile() 0 11 2
D loadComposerFile() 56 73 19
B makePathRelative() 0 24 7
A getManagedNamespaces() 0 3 1
C getPossibleFileNames() 0 64 10
A registerPsr0Namespace() 21 21 5
A registerPsr4Namespace() 21 21 5
A unfactorizeAutoload() 0 19 6

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(function($path) {
41
            return $path === '' ? '' : rtrim($path, '\\/').'/';
42
        }, $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(function($path) {
69
            return $path === '' ? '' : rtrim($path, '\\/').'/';
70
        }, $path);
71
72
        if (!isset($this->psr4Namespaces[$namespace])) {
73
            $this->psr4Namespaces[$namespace] = $paths;
74
        } else {
75
            $this->psr4Namespaces[$namespace] = array_merge($this->psr4Namespaces[$namespace], $paths);
76
        }
77
    }
78
79
    /**
80
     * @param string $composerJsonPath
81
     * @param string $rootPath
82
     * @param bool $useAutoloadDev
83
     * @return ClassNameMapper
84
     */
85
    public static function createFromComposerFile($composerJsonPath = null, $rootPath = null, $useAutoloadDev = false) {
86
        $classNameMapper = new ClassNameMapper();
87
88
        if ($composerJsonPath === null) {
89
            $composerJsonPath = __DIR__.'/../../../../composer.json';
90
        }
91
92
        $classNameMapper->loadComposerFile($composerJsonPath, $rootPath, $useAutoloadDev);
93
94
        return $classNameMapper;
95
    }
96
97
    /**
98
     *
99
     * @param string $composerJsonPath Path to the composer file
100
     * @param string $rootPath Root path of the project (or null)
101
     */
102
    public function loadComposerFile($composerJsonPath, $rootPath = null, $useAutoloadDev = false) {
103
        $composer = json_decode(file_get_contents($composerJsonPath), true);
104
105
        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...
106
            $relativePath = self::makePathRelative(dirname($composerJsonPath), $rootPath);
107
        } else {
108
            $relativePath = null;
109
        }
110
111 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...
112
            $psr0 = $composer["autoload"]["psr-0"];
113
            foreach ($psr0 as $namespace => $paths) {
114
                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...
115
                    if (!is_array($paths)) {
116
                        $paths = [$paths];
117
                    }
118
                    $paths = array_map(function($path) use ($relativePath) {
119
                        return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
120
                    }, $paths);
121
                }
122
                $this->registerPsr0Namespace($namespace, $paths);
123
            }
124
        }
125
126 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...
127
            $psr4 = $composer["autoload"]["psr-4"];
128
            foreach ($psr4 as $namespace => $paths) {
129
                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...
130
                    if (!is_array($paths)) {
131
                        $paths = [$paths];
132
                    }
133
                    $paths = array_map(function($path) use ($relativePath) {
134
                        return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
135
                    }, $paths);
136
                }
137
                $this->registerPsr4Namespace($namespace, $paths);
138
            }
139
        }
140
141
        if ($useAutoloadDev) {
142 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...
143
                $psr0 = $composer["autoload-dev"]["psr-0"];
144
                foreach ($psr0 as $namespace => $paths) {
145
                    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...
146
                        if (!is_array($paths)) {
147
                            $paths = [$paths];
148
                        }
149
                        $paths = array_map(function($path) use ($relativePath) {
150
                            return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
151
                        }, $paths);
152
                    }
153
                    $this->registerPsr0Namespace($namespace, $paths);
154
                }
155
            }
156
157 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...
158
                $psr4 = $composer["autoload-dev"]["psr-4"];
159
                foreach ($psr4 as $namespace => $paths) {
160
                    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...
161
                        if (!is_array($paths)) {
162
                            $paths = [$paths];
163
                        }
164
                        $paths = array_map(function($path) use ($relativePath) {
165
                            return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
166
                        }, $paths);
167
                    }
168
                    $this->registerPsr4Namespace($namespace, $paths);
169
                }
170
            }
171
        }
172
173
        return $this;
174
    }
175
176
    /**
177
     * Given an existing path, convert it to a path relative to a given starting path.
178
     * Shamelessly borrowed to Symfony :). Thanks guys.
179
     * Note: we do not include Symfony's "FileSystem" component to avoid adding too many dependencies.
180
     *
181
     * @param string $endPath Absolute path of target
182
     * @param string $startPath Absolute path where traversal begins
183
     *
184
     * @return string Path of target relative to starting path
185
     */
186
    private static function makePathRelative($endPath, $startPath)
187
    {
188
        // Normalize separators on Windows
189
        if ('\\' === DIRECTORY_SEPARATOR) {
190
            $endPath = strtr($endPath, '\\', '/');
191
            $startPath = strtr($startPath, '\\', '/');
192
        }
193
        // Split the paths into arrays
194
        $startPathArr = explode('/', trim($startPath, '/'));
195
        $endPathArr = explode('/', trim($endPath, '/'));
196
        // Find for which directory the common path stops
197
        $index = 0;
198
        while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
199
            $index++;
200
        }
201
        // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
202
        $depth = count($startPathArr) - $index;
203
        // Repeated "../" for each level need to reach the common path
204
        $traverser = str_repeat('../', $depth);
205
        $endPathRemainder = implode('/', array_slice($endPathArr, $index));
206
        // Construct $endPath from traversing to the common path, then to the remaining $endPath
207
        $relativePath = $traverser.(strlen($endPathRemainder) > 0 ? $endPathRemainder.'/' : '');
208
        return (strlen($relativePath) === 0) ? './' : $relativePath;
209
    }
210
211
    /**
212
     * Returns a list of all namespaces that are managed by the ClassNameMapper.
213
     *
214
     * @return string[]
215
     */
216
    public function getManagedNamespaces() {
217
        return array_keys(array_merge($this->psr0Namespaces, $this->psr4Namespaces));
218
    }
219
220
    /**
221
     * Returns a list of paths that can be used to store $className.
222
     *
223
     * @param string $className
224
     * @return string[]
225
     */
226
    public function getPossibleFileNames($className) {
227
        $possibleFileNames = array();
228
        $className = ltrim($className, '\\');
229
230
        $psr0unfactorizedAutoload = $this->unfactorizeAutoload($this->psr0Namespaces);
231
232
        foreach ($psr0unfactorizedAutoload as $result) {
233
            $namespace = $result['namespace'];
234
            $directory = $result['directory'];
235
236
            if ($namespace === '') {
237
                $tmpClassName = $className;
238
                if ($lastNsPos = strripos($tmpClassName, '\\')) {
239
                    $namespace = substr($tmpClassName, 0, $lastNsPos);
240
                    $tmpClassName = substr($tmpClassName, $lastNsPos + 1);
241
                }
242
243
                $fileName = str_replace('\\', '/', $namespace) . '/' . str_replace('_', '/', $tmpClassName) . '.php';
244
                $possibleFileNames[] = $directory.$fileName;
245
            } else {
246
                if (strpos($className, $namespace) === 0) {
247
                    $tmpClassName = $className;
248
                    $fileName  = '';
249
                    if ($lastNsPos = strripos($tmpClassName, '\\')) {
250
                        $namespace = substr($tmpClassName, 0, $lastNsPos);
251
                        $tmpClassName = substr($tmpClassName, $lastNsPos + 1);
252
                        $fileName  = str_replace('\\', '/', $namespace) . '/';
253
                    }
254
                    $fileName .= str_replace('_', '/', $tmpClassName) . '.php';
255
256
                    $possibleFileNames[] = $directory.$fileName;
257
                }
258
            }
259
        }
260
261
        $psr4unfactorizedAutoload = $this->unfactorizeAutoload($this->psr4Namespaces);
262
263
        foreach ($psr4unfactorizedAutoload as $result) {
264
            $namespace = $result['namespace'];
265
            $directory = $result['directory'];
266
267
            if ($namespace === '') {
268
                $fileName = str_replace('\\', '/', $className) . '.php';
269
                $possibleFileNames[] = $directory.$fileName;
270
            } else {
271
                if (strpos($className, $namespace) === 0) {
272
                    $shortenedClassName = substr($className, strlen($namespace));
273
274
                    if ($lastNsPos = strripos($shortenedClassName, '\\')) {
275
                        $namespace = substr($shortenedClassName, 0, $lastNsPos);
276
                        $shortenedClassName = substr($shortenedClassName, $lastNsPos + 1);
277
                        $fileName = str_replace('\\', '/', $namespace) . '/' . $shortenedClassName;
278
                    } else {
279
                        $fileName = $shortenedClassName;
280
                    }
281
                    $fileName .= '.php';
282
283
                    $possibleFileNames[] = $directory . $fileName;
284
                }
285
            }
286
        }
287
288
        return $possibleFileNames;
289
    }
290
291
    /**
292
     * Takes in parameter an array like
293
     * [{ "Mouf": "src/" }] or [{ "Mouf": ["src/", "src2/"] }] .
294
     * returns
295
     * [
296
     * 	{"namespace"=> "Mouf", "directory"=>"src/"},
297
     * 	{"namespace"=> "Mouf", "directory"=>"src2/"}
298
     * ]
299
     *
300
     * @param array $autoload
301
     * @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...
302
     */
303
    private static function unfactorizeAutoload(array $autoload) {
304
        $result  = array();
305
        foreach ($autoload as $namespace => $directories) {
306
            if (!is_array($directories)) {
307
                $result[] = array(
308
                    "namespace" => $namespace,
309
                    "directory" => $directories === '' ? '' : trim($directories, '/\\').'/'
310
                );
311
            } else {
312
                foreach ($directories as $dir) {
313
                    $result[] = array(
314
                        "namespace" => $namespace,
315
                        "directory" => $dir === '' ? '' : trim($dir, '/').'/'
316
                    );
317
                }
318
            }
319
        }
320
        return $result;
321
    }
322
}