Skip to content

Instantly share code, notes, and snippets.

@tentacode
Created July 5, 2022 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tentacode/0edba2a9709f6ae3164079c7ee7ded2a to your computer and use it in GitHub Desktop.
Save tentacode/0edba2a9709f6ae3164079c7ee7ded2a to your computer and use it in GitHub Desktop.
It fixes php namespaces (only namespaces, not use statements)
<?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