Skip to content

Instantly share code, notes, and snippets.

@tentacode
Created July 5, 2022 14:44
Show Gist options
  • Select an option

  • Save tentacode/0edba2a9709f6ae3164079c7ee7ded2a to your computer and use it in GitHub Desktop.

Select an option

Save tentacode/0edba2a9709f6ae3164079c7ee7ded2a to your computer and use it in GitHub Desktop.

Revisions

  1. tentacode created this gist Jul 5, 2022.
    64 changes: 64 additions & 0 deletions namespace-fixer.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,64 @@
    <?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);