Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Backslasher Laravel Package

nilportugues/php_backslasher

CLI tool that scans PHP code and prefixes internal functions/constants (plus true/false/null) with a leading backslash for faster resolution, especially with OPcache. Run php bin/php_backslasher fix to update a directory.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require --dev nilportugues/php_backslasher
    

    Add to composer.json under require-dev to ensure it’s only installed in development environments.

  2. First Run (Dry Run):

    php bin/php_backslasher fix app/
    

    Use --dry-run (if supported) or manually review changes with git diff to verify correctness.

  3. First Use Case:

    • Target a single directory (e.g., app/Http/Controllers) to test the tool’s behavior.
    • Focus on files with heavy use of internal functions (e.g., strlen, count, json_encode) or constants (e.g., PHP_EOL, JSON_PRETTY_PRINT).

Where to Look First

  • Laravel-Specific Files:
    • app/Providers/ (Service providers often use internal functions like app(), config(), route()).
    • app/Http/Controllers/ (Controllers frequently call response(), redirect(), abort()).
    • app/Helpers/ or custom utility files (likely to contain raw internal function calls).
  • Configuration Files:
    • config/ (e.g., app.php, filesystems.php) may use constants like DIRECTORY_SEPARATOR or PHP_INT_MAX.
  • Exclude:
    • vendor/ (risk of breaking third-party packages).
    • config/cache.php or generated files (may be overwritten).

Implementation Patterns

Usage Patterns

1. CI/CD Integration

Add to composer.json to run automatically after composer install:

"scripts": {
    "post-install-cmd": [
        "@php_backslasher"
    ],
    "php_backslasher": "php bin/php_backslasher fix app"
}
  • Pros: Enforces consistency across all environments.
  • Cons: May slow down composer install; exclude in production builds.

2. Git Hooks (Pre-Commit)

Use a pre-commit hook to catch unqualified internal functions before they’re merged:

# .git/hooks/pre-commit
#!/bin/bash
php bin/php_backslasher fix --dry-run app/ | grep -q "ERROR" && exit 1
  • Pros: Prevents regressions in namespaced code.
  • Cons: Requires developers to have the tool installed locally.

3. Artisan Command (Laravel-Specific)

Create a custom Artisan command for IDE-friendly execution:

// app/Console/Commands/BackslasherCommand.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class BackslasherCommand extends Command
{
    protected $signature = 'backslasher:fix {directory? : Directory to fix}';
    public function handle()
    {
        $directory = $this->argument('directory') ?? app_path();
        $this->call('vendor:publish', ['--provider' => 'nilportugues\php_backslasher\ServiceProvider']);
        shell_exec("php bin/php_backslasher fix {$directory}");
    }
}
  • Pros: Integrates with Laravel’s CLI workflow.
  • Cons: Adds complexity; may require publishing the tool’s assets.

4. Targeted Refactoring

Use the tool incrementally:

# Fix only files modified in the last week
git log --since="1 week ago" --name-only --pretty=format: | xargs php bin/php_backslasher fix
  • Pros: Reduces risk by focusing on recent changes.
  • Cons: Manual effort to track modified files.

Workflows

Laravel-Specific Workflow

  1. Setup:
    composer require --dev nilportugues/php_backslasher
    
  2. Test on a Subset:
    php bin/php_backslasher fix app/Http/Controllers --dry-run
    git diff
    
  3. Integrate into CI: Add to .github/workflows/laravel.yml:
    - name: Run BackSlasher
      run: composer php_backslasher
    
  4. Monitor:
    • Watch for false positives (e.g., custom functions named like built-ins).
    • Exclude directories like vendor/ or config/ if issues arise.

Performance Validation

  1. Before:
    php artisan tinker --bench --memory --iterations=100
    
    Measure baseline performance (e.g., route execution time).
  2. After: Run the tool, then re-benchmark.
    • Expected: 1–5% improvement in OPcache-enabled environments.
    • Note: Gains are most noticeable in high-traffic or latency-sensitive apps.

Integration Tips

  • Combine with PHP-CS-Fixer: Run php_backslasher before php-cs-fixer to avoid rework:
    "scripts": {
        "post-install-cmd": [
            "php bin/php_backslasher fix app",
            "@php-cs-fixer fix"
        ]
    }
    
  • Exclude Files: Use --exclude to skip sensitive files:
    php bin/php_backslasher fix app/ --exclude="app/Providers/AppServiceProvider.php"
    
  • Backup First: Always commit or stash changes before running the tool:
    git stash
    php bin/php_backslasher fix app/
    git diff --cached | grep -q "^+" && echo "Review changes before commit" && exit 1
    

Gotchas and Tips

Pitfalls

  1. False Positives:

    • Custom Functions/Constants: If your code defines a function or constant with the same name as a PHP built-in (e.g., strlen), the tool will incorrectly add a backslash.
      • Fix: Exclude directories or manually review changes.
    • Dynamic Calls: Tools like call_user_func('strlen') or create_function() will break.
      • Fix: Exclude files using these patterns or handle them manually.
  2. PHP 8+ Edge Cases:

    • New Syntax: The tool was last updated in 2020 and may misparse PHP 8+ features like:
      • Union types (array|string).
      • Match expressions (match ($x) { ... }).
      • Named arguments (str_contains($haystack, $needle, $offset)).
      • Fix: Test thoroughly on a PHP 8.1+ Laravel app before full adoption.
  3. Namespace Conflicts:

    • Global Functions: If your code uses use function declarations (e.g., use function strlen;), the tool may conflict.
      • Fix: Avoid use function for built-ins or exclude such files.
  4. Performance Myth:

    • OPcache Required: The tool only provides benefits when OPcache is enabled. Verify with:
      php -i | grep opcache.enable
      
    • Negligible Gain: For small codebases or non-namespaced apps, the impact may be <1%.
  5. Tool Limitations:

    • No IDE Support: Changes are file-based; IDEs won’t recognize the refactoring (e.g., no "Go to Definition" for \strlen).
    • No Undo: The tool modifies files in-place. Always review changes with git diff first.

Debugging Tips

  1. Dry Run: Simulate changes without modifying files:

    php bin/php_backslasher fix app/ --dry-run  # If supported
    # Or manually:
    git stash
    php bin/php_backslasher fix app/
    git diff --cached
    git stash pop
    
  2. Log Output: Redirect output to a file for review:

    php bin/php_backslasher fix app/ > backslasher.log 2>&1
    
  3. Test on a Clone: Work on a fresh clone of the repo to avoid accidental merges:

    git clone <repo> temp-fix
    cd temp-fix
    composer install
    php bin/php_backslasher fix app/
    

Configuration Quirks

  1. Symfony Console Dependency: The tool requires symfony/console (v2–4). If missing, install it:

    composer require symfony/console "^4"
    
  2. Zend Code Dependency: The tool uses zendframework/zend-code (v3). Laravel may not include this by default:

    composer require zendframework/zend-code:~3
    
  3. Case Sensitivity: The tool is case-sensitive. Ensure your filesystem and editor preserve case (e.g., strlen vs. StrLen).

Extension Points

  1. Custom Rules: Extend the tool by modifying its core logic (
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky