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

Coding Standard Laravel Package

lcobucci/coding-standard

PHPCS coding standard based on Doctrine’s rules with a few tweaks. Provides a reusable ruleset to enforce consistent PHP code style across projects, suitable for CI checks and team-wide formatting conventions.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package via Composer in your Laravel project:

    composer require --dev lcobucci/coding-standard
    
  2. Run PHPCS against your codebase:

    vendor/bin/phpcs --standard=lcobucci src/
    
    • Replace src/ with your target directory (e.g., app/, tests/).
  3. Fix violations automatically (if using php-cs-fixer):

    vendor/bin/php-cs-fixer fix --rules=@lcobucci
    

First Use Case: CI Pipeline Integration

Add a GitHub Actions workflow (.github/workflows/coding-standard.yml):

name: Coding Standard
on: [push, pull_request]

jobs:
  phpcs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: shivammathur/setup-php@v2
        with:
          php-version: '8.4'
      - run: composer install --dev
      - run: vendor/bin/phpcs --standard=lcobucci --warning-severity=0 src/

Implementation Patterns

Workflow: Local Development

  1. Pre-commit Hook (using php-cs-fixer):

    composer require --dev php-cs-fixer
    vendor/bin/php-cs-fixer fix --rules=@lcobucci --dry-run
    
    • Add to .git/hooks/pre-commit:
      #!/bin/sh
      vendor/bin/php-cs-fixer fix --rules=@lcobucci --dry-run || exit 1
      
  2. VS Code Integration:

    • Install the PHP Intelephense extension.
    • Configure settings.json:
      {
        "php-cs-fixer.executablePath": "vendor/bin/php-cs-fixer",
        "php-cs-fixer.rules": "@lcobucci",
        "editor.codeActionsOnSave": {
          "source.fixAll.php-cs-fixer": true
        }
      }
      

Workflow: Team Onboarding

  1. Document the Standard:

    • Add a CONTRIBUTING.md section:
      ## Coding Standards
      This project enforces [Lcobucci's PHP Coding Standard](https://github.com/lcobucci/coding-standard).
      Run `composer cs-check` to validate your changes.
      
    • Link to the Doctrine CS docs for context.
  2. Pair Programming:

    • Use phpcs --diff to review changes:
      vendor/bin/phpcs --standard=lcobucci --diff src/old-file.php src/new-file.php
      

Integration Tips

  • Laravel Mix/Webpack: Add a custom script to webpack.mix.js:

    mix.postCss('resources/css/app.css', 'public/css', [
      require('postcss-import'),
      require('tailwindcss'),
    ]);
    mix.scripts(['resources/js/app.js'], 'public/js');
    mix.after(() => {
      require('shelljs/global');
      exec('vendor/bin/phpcs --standard=lcobucci --warning-severity=0 src/');
    });
    
  • PHPStan Integration: Combine with PHPStan for static analysis:

    composer require --dev phpstan/phpstan
    vendor/bin/phpstan analyse --level=5 src/ 2>&1 | vendor/bin/phpcs --standard=lcobucci -- --
    
  • Custom Rulesets: Extend the standard in .phpcs.xml:

    <config defaultStandard="lcobucci">
      <arg name="tab-width" value="4"/>
      <rule ref="lcobucci">
        <exclude name="Generic.Files.LineEndings"/>
      </rule>
      <rule ref="SlevomatCodingStandard.TypeHints">
        <exclude name="TypeHints.DisallowMixedTypeHint"/>
      </rule>
    </config>
    

Gotchas and Tips

Pitfalls

  1. PHP Version Mismatch:

    • The package requires PHP 8.4+ and PHPCS 4.0+. Running on older versions will fail silently or produce incorrect results.
    • Fix: Update your php.ini or use a Docker container:
      FROM php:8.4-cli
      RUN pecl install ast
      
  2. False Positives in Legacy Code:

    • Rules like Arrays.DisallowImplicitCreation may flag legacy code (e.g., array('key' => 'value')).
    • Fix: Use <exclude-pattern>...</exclude-pattern> in .phpcs.xml:
      <exclude-pattern>*/legacy/*</exclude-pattern>
      
  3. Attribute Formatting:

    • The standard enforces strict attribute alignment (e.g., [Attribute(foo: 'bar')]). Mixing styles (e.g., [Attribute(foo: 'bar')]) will trigger violations.
    • Fix: Run php-cs-fixer with:
      vendor/bin/php-cs-fixer fix --rules=@lcobucci --allow-risky=yes
      
  4. DocBlock Inconsistencies:

    • Methods without docblocks or with incorrect @param/@return tags will fail. Laravel’s IDE helpers (e.g., phpdoc:generate) can auto-fix these:
      composer require --dev barryvdh/laravel-ide-helper
      vendor/bin/phpdoc -d src/ -t docs/
      

Debugging

  • Verbose Output: Run PHPCS with -v to see which rules are failing:

    vendor/bin/phpcs -v --standard=lcobucci src/
    

    Example output:

    FILE: src/Controller/UserController.php
    ----------------------------------------------------------------------
    FOUND 2 ERROR(S) AND 1 WARNING(S) AFFECTING 2 LINE(S)
    ----------------------------------------------------------------------
    12 | ERROR   | [x] Arrays.DisallowImplicitCreation: Implicit array creation
       found; use array() syntax
    15 | WARNING | [ ] Generic.Files.LineEndings: Line ending style must be
    consistent
    
  • Rule-Specific Fixes:

    • For Arrays.DisallowImplicitCreation, use:
      vendor/bin/php-cs-fixer fix --rules=@lcobucci --allow-risky=yes
      
    • For PSR12.Methods.MethodDeclaration, ensure methods are declared as:
      public function methodName(): ReturnType
      

Extension Points

  1. Custom Sniffs: Add a Sniffs directory and reference it in .phpcs.xml:

    <rule ref="lcobucci">
      <file>app/Sniffs/</file>
    </rule>
    
  2. Overriding Rules: Disable specific rules in .phpcs.xml:

    <rule ref="lcobucci">
      <exclude name="PSR12.Namespaces.UnusedUses"/>
    </rule>
    
  3. Parallel Execution: Speed up large codebases with --parallel:

    vendor/bin/phpcs --standard=lcobucci --parallel=8 src/
    

Pro Tips

  • CI Caching: Cache PHPCS dependencies in GitHub Actions:

    - uses: actions/cache@v3
      with:
        path: vendor
        key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
    
  • Interactive Mode: Use --interactive to fix violations manually:

    vendor/bin/phpcs --standard=lcobucci --interactive src/
    
  • Laravel Artisan Command: Create a custom command (app/Console/Commands/CheckCs.php):

    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    use Symfony\Component\Process\Process;
    
    class CheckCs extends Command
    {
        protected $signature = 'cs:check';
        protected $description = 'Run Lcobucci coding standard checks';
    
        public function handle()
        {
            $process = new Process(['vendor/bin/phpcs', '--standard=lcobucci', '--warning-severity=0', 'src/']);
            $process->run();
    
            if (!$process->isSuccessful()) {
                $this->error($process->getOutput());
                exit(1);
            }
    
            $this->info('Coding standards check passed!');
        }
    }
    

    Register in app/Console/Kernel.php:

    protected $commands = [
        Commands\CheckCs::class,
    ];
    

    Run with:

    php artisan cs:check
    
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata