Created
July 5, 2022 14:44
-
-
Save tentacode/0edba2a9709f6ae3164079c7ee7ded2a to your computer and use it in GitHub Desktop.
It fixes php namespaces (only namespaces, not use statements)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function usage_error(): void | |
{ | |
echo 'Usage: php namespace-fixer.php <path> <prefix>' . PHP_EOL; | |
echo 'Example: php namespace-fixer.php src App' . PHP_EOL; | |
exit(1); | |
} | |
$globalPath = $argv[1] ?? usage_error(); | |
$prefix = $argv[2] ?? usage_error(); | |
echo sprintf( | |
'Fixing namespaces, prefixed by "%s", in %s.', | |
$prefix, | |
$globalPath | |
). PHP_EOL; | |
function fix_files(string $globalPath, string $path, string $prefix): void | |
{ | |
$files = scandir($path); | |
foreach ($files as $file) { | |
if ($file === '.' || $file === '..') { | |
continue; | |
} | |
$filePath = $path . '/' . $file; | |
if (is_dir($filePath)) { | |
fix_files($globalPath, $filePath, $prefix); | |
continue; | |
} | |
if (strpos($file, '.php') === false) { | |
continue; | |
} | |
echo 'Fixing ' . $file . PHP_EOL; | |
$content = file_get_contents($filePath); | |
$expectedNamespace = str_replace([ | |
trim($globalPath, '/'), | |
'/', | |
], [ | |
'App', | |
'\\', | |
], $path); | |
$content = preg_replace_callback( | |
'/(?<!\w)(namespace [^;]+);/', | |
function ($matches) use ($expectedNamespace) { | |
return 'namespace '.$expectedNamespace.';'; | |
}, | |
$content | |
); | |
file_put_contents($filePath, $content); | |
} | |
} | |
fix_files($globalPath, $globalPath, $prefix); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment