Strauss PHP Namespace Renamer

repository·master·Indexed 41 days ago

https://github.com/brianhenryie/strauss

A PHP tool designed to prefix namespaces, classnames, and constants in PHP files to isolate dependencies and avoid autoloading collisions. It is particularly useful for environments like WordPress where multiple plugins may use different versions of the same library. Strauss can be installed as a .phar file or a Composer dependency and supports automated prefixing via composer.json configuration.

Tokens
5.7K
Snippets
17
Records
21
Agent score
39%

What's inside Strauss

  1. Install Strauss as a dev dependency via Composer (not recommended)

    master

    You can install Strauss as a development dependency, though this method is not recommended and behavior may vary.

    1. Install the package: Run composer require --dev brianhenryie/strauss.
    2. Configure Composer: Update your composer.json scripts to use the strauss command directly.
    composer require --dev brianhenryie/strauss
    "scripts": {
        "prefix-namespaces": [
            "strauss",
            "@php composer dump-autoload"
        ],
        "post-install-cmd": [
            "@prefix-namespaces"
        ],
        "post-update-cmd": [
            "@prefix-namespaces"
        ],
        "post-autoload-dump": [
            "strauss include-autoloader"
        ]
    }
  2. Install Strauss as a .phar file (recommended)

    master

    The recommended way to install Strauss is as a .phar file located in a bin/ directory. This method includes a Composer script that automatically downloads the .phar if it is missing.

    1. Prepare the directory: Create a bin/ directory and a .gitkeep file to ensure the directory is tracked by Git.
    2. Ignore the binary: Add bin/strauss.phar to your .gitignore file.
    3. Configure Composer: Add the prefix-namespaces script and relevant Composer hooks to your composer.json to automate downloading, prefixing, and autoloading.
    # Create bin directory
    mkdir bin
    touch bin/.gitkeep

    Add to .gitignore

    bin/strauss.phar

    Add to composer.json scripts

    "scripts": { "prefix-namespaces": [ "sh -c 'test -f ./bin/strauss.phar || mkdir bin && curl -o bin/strauss.phar -L -C - https://github.com/BrianHenryIE/strauss/releases/latest/download/strauss.phar'", "@php bin/strauss.phar", "@php -d memory_limit=1G bin/strauss.phar --info", "@composer dump-autoload" ], "post-install-cmd": [ "@prefix-namespaces" ], "post-update-cmd": [ "@prefix-namespaces" ], "post-autoload-dump": [ "@php bin/strauss.phar include-autoloader" ] }

  3. How to use the Strauss autoloader

    master

    Strauss generates a set of autoload files in your target_directory and provides an autoload.php file.

    To use the prefixed code in your project, require the generated autoloader:

    require_once __DIR__ . '/vendor-prefixed/autoload.php';

    Integration Strategies:

    • Standalone: If you don't plan to use Composer's original autoloader, enable include_root_autoload: true in your Strauss config. This allows you to require only the Strauss autoloader.
    • Hybrid: If you want to continue using Composer's autoloader alongside Strauss, you can run strauss include-autoloader to append a line to vendor/autoload.php that includes the Strauss autoloader.
    • Cleanup: If you want to replace the original vendor packages entirely, set delete_vendor_packages: true and set your target_directory to vendor.
  4. Disable optimized/classmap-authoritative autoload generation

    master

    By default, Strauss sets optimize_autoloader to true. To disable optimized/classmap-authoritative Composer autoload generation, set this key to false in your extra/strauss configuration.

    {
      "extra": {
        "strauss": {
          "optimize_autoloader": false
        }
      }
    }
  5. Configure Strauss in composer.json

    master

    Strauss can be configured by adding an extra/strauss object to your composer.json. While it works with zero configuration by inferring values from your autoload or name keys, you can customize the prefixing behavior, target directory, and exclusions.

    Key inferred settings:

    • target_directory: The directory where prefixed files are copied (defaults to vendor-prefixed).
    • namespace_prefix: The string prefixed to each namespace.
    • classmap_prefix: The string prefixed to class names in the global namespace.
    • packages: The list of packages to process. If omitted, all packages in the require key are included.
    • classmap_output: A boolean determining if Strauss creates autoload-classmap.php and autoload.php. It defaults to true if target_directory is NOT in your project's autoload key, and false otherwise.
    "extra": {
        "strauss": {
            "target_directory": "vendor-prefixed",
            "namespace_prefix": "BrianHenryIE\\My_Project\\",
            "classmap_prefix": "BrianHenryIE_My_Project_",
            "constant_prefix": "BHMP_",
            "packages": [],
            "update_call_sites": false,
            "include_root_autoload": false,
            "optimize_autoloader": true,
            "override_autoload": {},
            "exclude_from_copy": {
                "packages": [],
                "namespaces": [],
                "file_patterns": []
            },
            "exclude_from_prefix": {
                "packages": [],
                "namespaces": [],
                "file_patterns": []
            },
            "exclude_constants": {
                "packages": [],
                "namespaces": [],
                "file_patterns": [],
                "constants": []
            },
            "exclude_from_string_rename": {
                "functions": []
            },
            "namespace_replacement_patterns" : {},
            "delete_vendor_packages": false,
            "delete_vendor_files": false,
            "exclude_git_files": true
        }
    }
  6. Automate autoloader injection via Composer

    master

    To ensure that Strauss aliases are always loaded even after running composer dump-autoload, add the include-autoloader command to your composer.json under the scripts section using the post-dump-autoload event.

    Note: This command does not generate the autoload_aliases.php files; it only modifies vendor/autoload.php to include them.

    {
        "scripts": {
            "post-dump-autoload": "strauss include-autoloader"
        }
    }
  7. Review breaking changes in Strauss

    master

    If you are upgrading from an older version of Strauss, be aware of the following behavior changes that may affect your workflow:

    • v0.25.0: The tool now copies all files from a package to the target directory.
    • v0.21.0: Global functions are now prefixed.
    • v0.16.0: PHP built-in classes found in polyfill packages are no longer prefixed.
    • v0.14.0: psr/* packages are no longer excluded by default.
    • v0.12.0: The default output target_directory changed from strauss to vendor-prefixed.
  8. Configure Strauss via composer.json

    master

    Strauss can be configured by adding an extra.strauss section to your composer.json file. This allows you to control how packages are copied, prefixed, and how call sites are updated.

    Note that Strauss supports several configuration patterns, including snake_case keys (e.g., target_directory) which are automatically mapped to the internal configuration schema. It also maintains backward compatibility with Mozart configuration keys.

    {
        "extra": {
            "strauss": {
                "target_directory": "vendor-prefixed",
                "dep_namespace": "My_Project_Namespace\\dep_directory",
                "exclude_packages": ["vendor/package-to-skip"],
                "delete_vendor_files": true,
                "update_call_sites": ["src", "tests"]
            }
        }
    }
  9. Configure Strauss verbosity and dry runs

    master

    When running Strauss, you can control the output verbosity or perform a trial run without modifying any files.

    Flags:

    • --dry-run: Test the process without making any changes to your files.
    • --notice: Default verbosity.
    • --info: Increased verbosity.
    • --debug: Maximum verbosity.
    • --silent: No output.
    # Perform a dry run
    composer -- prefix-namespaces --dry-run
    
    # Run with debug verbosity
    composer -- prefix-namespaces --debug
  10. Reference: Strauss Configuration Options

    master

    The following configuration keys are available within the extra/strauss object in composer.json.

    ### Core Settings
    - `target_directory` (string): Directory to copy files to. Default: `vendor-prefixed`.
    - `namespace_prefix` (string): Default string to prefix each namespace.
    - `classmap_prefix` (string): Default string to prefix class names in the global namespace.
    - `constant_prefix` (string): Prefix for `define()` calls (e.g., `define("A", 1)` -> `define("PREFIX_A", 1)`).
    - `packages` (array): List of packages to process. If absent, all `require` packages are included.
    - `update_call_sites` (bool|array): If `true`, updates PHP files in the project's `autoload` directories to use prefixed classes. If an `array`, uses specific paths.
    - `include_root_autoload` (bool): If `true`, includes the project's root autoload section in the Strauss autoloader.
    - `optimize_autoloader` (bool): If `true`, forces optimized/classmap-authoritative autoload generation. Default: `true`.
    - `exclude_git_files` (bool): If `true`, skips files ignored by `.gitignore` or marked `export-ignore` in `.gitattributes`. Default: `true`.
    - `delete_vendor_packages` (bool): If `true`, deletes the original vendor directories after processing. Default: `false`.
    - `delete_vendor_files` (bool): If `true`, deletes files copied from vendor directories after processing. Default: `false`.
    - `include_modified_date` (bool): Includes date in PHPdoc headers. Default: `true`.
    - `include_author` (bool): Includes author name in PHPdoc headers. Default: `true`.
    
    ### Overrides and Exclusions
    - `override_autoload` (dictionary): Keyed by package name; replaces the original package's `autoload` property.
    - `exclude_from_copy` (object):
        - `packages` (array): Package names to skip.
        - `namespaces` (array): Exact match namespaces to skip.
        - `file_patterns` (array): Regex patterns for filenames to skip.
    - `exclude_from_prefix` (object): Symbols in these files/packages won't be renamed (but their usage will be updated).
        - `file_patterns` (array): Regex patterns for file paths.
        - `packages` (array): Package names to exclude.
        - `namespaces` (array): Exact match namespaces to exclude.
    - `exclude_constants` (object): Prevents prefixing of constants (e.g., `define` or `const`).
        - `packages` (array): Package names to exclude.
        - `namespaces` (array): Prefix match namespaces to exclude.
        - `file_patterns` (array): Regex patterns for file paths.
        - `constants` (array): Specific constant names to never prefix (e.g., `["WP_PLUGIN_DIR", "ABSPATH"]`).
    - `exclude_from_string_rename` (object):
        - `functions` (array): Global function names to leave unchanged inside strings (e.g., `["value", "when"]`).
    - `namespace_replacement_patterns` (dictionary): `preg_replace` patterns to use instead of `namespace_prefix`.
  11. Handle symlinked packages in Strauss

    master

    Strauss requires actual files to be present in the vendor directory to perform renaming and copying. If you are using symlinked packages (e.g., via path repositories in Composer), Strauss will throw an error.

    To resolve this, use the following environment variable when running composer install to ensure packages are copied to the vendor directory instead of symlinked:

    COMPOSER_MIRROR_PATH_REPOS=1 composer install