1 | <?php |
||
7 | class NamespaceCorrector |
||
8 | { |
||
9 | public static function getNamespaceFromFullClass($class) |
||
10 | { |
||
11 | $segments = explode('\\', $class); |
||
12 | array_pop($segments); // removes the last part |
||
13 | |||
14 | return trim(implode('\\', $segments), '\\'); |
||
15 | } |
||
16 | |||
17 | public static function haveSameNamespace($class1, $class2) |
||
18 | { |
||
19 | return self::getNamespaceFromFullClass($class1) == self::getNamespaceFromFullClass($class2); |
||
20 | } |
||
21 | |||
22 | public static function fix($classFilePath, $incorrectNamespace, $correctNamespace) |
||
23 | { |
||
24 | // decides to add namespace (in case there is no namespace) or edit the existing one. |
||
25 | [$oldLine, $newline] = self::getNewLine($incorrectNamespace, $correctNamespace); |
||
26 | |||
27 | $oldLine = \ltrim($oldLine, '\\'); |
||
28 | FileManipulator::replaceFirst($classFilePath, $oldLine, $newline); |
||
29 | } |
||
30 | |||
31 | public static function calculateCorrectNamespace($relativeClassPath, $composerPath, $rootNamespace) |
||
32 | { |
||
33 | // removes the filename.php from the end of the string |
||
34 | $classPath = \explode(DIRECTORY_SEPARATOR, $relativeClassPath); |
||
35 | // removes the filename |
||
36 | array_pop($classPath); |
||
37 | // ensure back slashes. |
||
38 | $classPath = \implode('\\', $classPath); |
||
39 | |||
40 | $composerPath = \str_replace('/', '\\', $composerPath); |
||
41 | |||
42 | // replace composer base_path with composer namespace |
||
43 | /** |
||
44 | * "psr-4": { |
||
45 | * "App\\": "app/" |
||
46 | * }. |
||
47 | */ |
||
48 | return Str::replaceFirst(\trim($composerPath, '\\'), \trim($rootNamespace, '\\/'), $classPath); |
||
49 | } |
||
50 | |||
51 | private static function getNewLine($incorrectNamespace, $correctNamespace) |
||
52 | { |
||
53 | if ($incorrectNamespace) { |
||
54 | return [$incorrectNamespace, $correctNamespace]; |
||
55 | } |
||
56 | |||
57 | // In case there is no namespace specified in the file: |
||
58 | return ['<?php', '<?php'.PHP_EOL.PHP_EOL.'namespace '.$correctNamespace.';'.PHP_EOL]; |
||
59 | } |
||
60 | |||
61 | public static function getRelativePathFromNamespace($namespace) |
||
72 | |||
73 | public static function getNamespaceFromRelativePath($relPath, $autoload = null) |
||
74 | { |
||
75 | // Remove .php from class path |
||
76 | $relPath = str_replace([base_path(), '.php'], '', $relPath); |
||
77 | |||
90 | } |
||
91 |
This error can happen if you refactor code and forget to move the variable initialization.
Let’s take a look at a simple example:
The above code is perfectly fine. Now imagine that we re-order the statements:
In that case,
$x
would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.