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:
1 | <?php |
||
24 | final class Psr4Mapping implements PsrAutoloaderMapping |
||
25 | { |
||
26 | /** @var array<string, array<int, string>> */ |
||
27 | private $mappings = []; |
||
28 | |||
29 | private function __construct() |
||
30 | { |
||
31 | } |
||
32 | |||
33 | /** @param array<string, array<int, string>> $mappings */ |
||
34 | View Code Duplication | public static function fromArrayMappings(array $mappings) : self |
|
|
|||
35 | { |
||
36 | self::assertValidMapping($mappings); |
||
37 | |||
38 | $instance = new self(); |
||
39 | |||
40 | $instance->mappings = array_map( |
||
41 | static function (array $directories) : array { |
||
42 | return array_map(static function (string $directory) : string { |
||
43 | return rtrim($directory, '/'); |
||
44 | }, $directories); |
||
45 | }, |
||
46 | $mappings |
||
47 | ); |
||
48 | |||
49 | return $instance; |
||
50 | } |
||
51 | |||
52 | /** {@inheritDoc} */ |
||
53 | public function resolvePossibleFilePaths(Identifier $identifier) : array |
||
54 | { |
||
55 | if (! $identifier->isClass()) { |
||
56 | return []; |
||
57 | } |
||
58 | |||
59 | $className = $identifier->getName(); |
||
60 | $matchingPrefixes = $this->matchingPrefixes($className); |
||
61 | |||
62 | return array_values(array_filter(array_merge( |
||
63 | [], |
||
64 | ...array_map(static function (array $paths, string $prefix) use ($className) : array { |
||
65 | $subPath = ltrim(str_replace('\\', '/', substr($className, strlen($prefix))), '/'); |
||
66 | |||
67 | if ($subPath === '') { |
||
68 | return []; |
||
69 | } |
||
70 | |||
71 | return array_map(static function (string $path) use ($subPath) : string { |
||
72 | return rtrim($path, '/') . '/' . $subPath . '.php'; |
||
73 | }, $paths); |
||
74 | }, $matchingPrefixes, array_keys($matchingPrefixes)) |
||
75 | ))); |
||
76 | } |
||
77 | |||
78 | /** @return array<string, array<int, string>> */ |
||
79 | private function matchingPrefixes(string $className) : array |
||
89 | |||
90 | /** {@inheritDoc} */ |
||
91 | public function directories() : array |
||
95 | |||
96 | /** |
||
97 | * @param array<string, array<int, string>> $mappings |
||
98 | * |
||
99 | * @throws InvalidPrefixMapping |
||
100 | */ |
||
101 | View Code Duplication | private static function assertValidMapping(array $mappings) : void |
|
119 | } |
||
120 |
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.