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

Phpcb Laravel Package

covex-nn/phpcb

PHP Code Beautifier (phpcb) for formatting and cleaning up PHP codebases. Helps apply consistent styling, improve readability, and standardize code output across projects and teams, suitable for use in local workflows or automation.

View on GitHub
Deep Wiki
Context7

Implementation Patterns

Laravel-Specific Workflows

1. Artisan Command Wrapper

Leverage Laravel’s Artisan system to encapsulate phpcb logic:

// app/Console/Commands/GenerateCodeBrowser.php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Process\Process;
use Illuminate\Support\Facades\Storage;

class GenerateCodeBrowser extends Command
{
    protected $signature = 'phpcb:generate
                            {--path= : Target directory (default: app)}
                            {--sniffer= : Path to PHP_CodeSniffer XML report}
                            {--phpmd= : Path to PHPMD XML report}
                            {--output= : Output directory (default: storage/app/phpcb)}';

    protected $description = 'Generate a browsable code representation with QA violations highlighted';

    public function handle()
    {
        $path = $this->option('path') ?: app_path();
        $outputDir = $this->option('output') ?: storage_path('app/phpcb');

        $process = new Process([
            'php', 'vendor/bin/phpcb',
            $path,
            '--output-dir=' . $outputDir,
        ]);

        if ($snifferReport = $this->option('sniffer')) {
            $process->add('--sniffer-report=' . $snifferReport);
        }

        if ($phpmdReport = $this->option('phpmd')) {
            $process->add('--phpmd-report=' . $phpmdReport);
        }

        $process->run();

        if (!$process->isSuccessful()) {
            $this->error($process->getErrorOutput());
            return 1;
        }

        $this->info("Code browser generated at: {$outputDir}");
        $this->info("View report at: " . route('phpcb.view'));
    }
}

Register in AppServiceProvider:

public function boot()
{
    if ($this->app->runningInConsole()) {
        $this->commands([
            Commands\GenerateCodeBrowser::class,
        ]);
    }
}

2. CI/CD Pipeline Integration

Use Laravel’s task scheduling or GitHub Actions:

# .github/workflows/phpcb.yml
name: PHP Code Browser
on: [push, pull_request]

jobs:
  phpcb:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-php@v2
        with:
          php-version: '8.1'
      - run: composer install
      - run: ./vendor/bin/phpcs --report=xml > sniffer-report.xml
      - run: ./vendor/bin/phpcb ./app --sniffer-report=sniffer-report.xml --output-dir=phpcb_output
      - uses: actions/upload-artifact@v2
        with:
          name: phpcb-report
          path: phpcb_output/

3. Dynamic Report Serving

Serve reports via Laravel routes:

// routes/web.php
Route::get('/phpcb', function () {
    $outputDir = storage_path('app/phpcb');
    $indexPath = $outputDir . '/index.html';

    if (!file_exists($indexPath)) {
        abort(404);
    }

    return response()->file($indexPath);
})->name('phpcb.view');

4. Event-Driven Workflows

Trigger phpcb after QA tools run:

// app/Providers/EventServiceProvider.php
protected $listen = [
    'illuminate\events\ArtisanStarting' => [
        'App\Listeners\RunPHPCodeBrowser',
    ],
];
// app/Listeners/RunPHPCodeBrowser.php
public function handle()
{
    if (Artisan::getInput()['command'] === 'sniffs') {
        Artisan::call('phpcb:generate', [
            '--sniffer' => storage_path('app/sniffer-report.xml'),
        ]);
    }
}

Advanced Patterns

1. Custom Report Parsers

Extend covex-nn\PHP_CodeBrowser\Contracts\ReportParser for non-standard QA tools:

// app/Services/CustomParser.php
namespace App\Services;

use covex-nn\PHP_CodeBrowser\Contracts\ReportParser;
use SimpleXMLElement;

class CustomParser implements ReportParser
{
    public function parse(string $reportPath): array
    {
        $xml = simplexml_load_file($reportPath);
        $violations = [];

        foreach ($xml->file as $file) {
            foreach ($file->violation as $violation) {
                $violations[] = [
                    'file' => (string) $file['name'],
                    'line' => (int) $violation['line'],
                    'message' => (string) $violation['message'],
                    'severity' => (string) $violation['severity'],
                ];
            }
        }

        return $violations;
    }
}

Register in phpcb config:

// config/phpcb.php
'parsers' => [
    'custom' => App\Services\CustomParser::class,
],

2. Laravel Notifications for Violations

Integrate with Laravel Notifications to alert teams:

// app/Console/Commands/GenerateCodeBrowser.php
public function handle()
{
    // ... (existing code)

    $violations = $this->parseReport($outputDir);
    if (count($violations) > 0) {
        Notification::route('mail', ['team@example.com'])
                    ->notify(new CodeViolationNotification($violations));
    }
}

3. Incremental Analysis

Cache results to avoid full scans:

// app/Services/IncrementalAnalyzer.php
public function analyze(string $path, string $cachePath): bool
{
    if (file_exists($cachePath) && filemtime($cachePath) > filemtime($path)) {
        $this->info('Using cached analysis');
        return true;
    }

    Artisan::call('phpcb:generate', ['--path' => $path]);
    file_put_contents($cachePath, time());
    return false;
}

4. Dockerized Analysis

Run phpcb in a container for consistency:

# Dockerfile
FROM composer:latest
WORKDIR /app
COPY . .
RUN composer install && ./vendor/bin/phpcb ./app --output-dir=/app/phpcb_output

Laravel Forge/Deployer Integration:

// deploy.php
task('phpcb', function () {
    run('docker build -t phpcb-analyzer .');
    run('docker run --rm -v $(pwd):/app phpcb-analyzer');
});

Gotchas and Tips

Common Pitfalls

1. Permission Issues

  • Symptom: phpcb fails to write output files.
  • Fix: Ensure the web server user (e.g., www-data) has write permissions:
    chmod -R 775 storage/app/phpcb
    chown -R www-data:www-data storage/app/phpcb
    

2. Memory Limits

  • Symptom: phpcb crashes with "Allowed memory exhausted."
  • Fix: Increase PHP memory limit in php.ini or run in a container:
    docker run --memory=2G -v $(pwd):/app php:8.1-cli ./vendor/bin/phpcb ./app
    

3. False Positives in Laravel Code

  • Symptom: PHP_CodeSniffer flags Laravel-specific patterns (e.g., Facades, Blade directives).
  • Fix: Customize rules in .phpcs.xml:
    <rule ref="PSR12">
        <exclude name="PSR12.Files.SideEffectsComment.Missing" />
    </rule>
    

4. Outdated Dependencies

  • Symptom: phpcb fails due to incompatible Symfony Console.
  • Fix: Pin dependencies in composer.json:
    "require": {
        "symfony/console": "^5.4",
        "covex-nn/phpcb": "dev-main"
    }
    

5. CI/CD Timeouts

  • Symptom: phpcb exceeds GitHub Actions timeout (6 hours).
  • Fix: Split analysis into smaller chunks or use a self-hosted runner.

Debugging Tips

1. Verbose Output

Enable debug mode:

./vendor/bin/phpcb ./app --verbose

2. Log Violations

Redirect phpcb output to Laravel logs:

// In your Artisan command
$process = new Process([...]);
$process->setTimeout(null); // Disable timeout
$process->run(function ($type, $buffer) {
    if ($type === Process::ERR) {
        Log::error($buffer);
    } else {
        Log::info($buffer);
    }
});

3. Validate Reports

Check XML reports manually:

./vendor/bin/phpcs --report=xml --standard=PSR12 ./app > sniffer-report.xml
xmllint --format sniffer-report.xml

4. Test Incrementally

Analyze a single file first:

./vendor/bin/phpcb ./app/Http/Controllers/ --sn
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.
ilhamsyabani/laravel-volt-starter
thethunderturner/filament-latex
ghostcompiler/laravel-querybuilder
webrek/laravel-telescope-mongodb
anousss007/blatui
zatona-eg/zatona-eg-api
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat