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 Code Validator Laravel Package

flyeralarm/php-code-validator

FLYERALARM PHP coding guideline validator: a PSR-12 based PHP_CodeSniffer ruleset with extra standards like lowerCamelCase variables, no Yoda conditions, bans on eval/goto, namespace underscores, and certain class suffixes. Easy Composer embed via ruleset.xml.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel Projects

  1. Install as a dev dependency:
    composer require --dev flyeralarm/php-code-validator
    
  2. Add a phpcs.xml in your project root (example below) to reference the ruleset:
    <?xml version="1.0"?>
    <ruleset name="Laravel Project Rules">
        <file>./app/</file>
        <file>./tests/</file>
        <arg value="sp"/>
    
        <!-- Reference FLYERALARM's ruleset -->
        <rule ref="vendor/flyeralarm/php-code-validator/ruleset.xml"/>
    
        <!-- Override or extend rules (optional) -->
        <config name="categories" value="PSR12,FLYERALARM"/>
        <config name="tab-width" value="4"/>
    </ruleset>
    
  3. Run a quick check:
    vendor/bin/phpcs
    
    • Use --diff to compare against a baseline:
      vendor/bin/phpcs --diff=origin/main .
      

First Use Case: Pre-Commit Hook

Integrate with Laravel Forge or Git hooks to block non-compliant code:

# Add to `.git/hooks/pre-commit` (or use `husky`/`pre-commit`)
#!/bin/sh
vendor/bin/phpcs --standard=vendor/flyeralarm/php-code-validator/ruleset.xml --colors --report=full .
if [ $? -ne 0 ]; then
    echo "❌ Code style violations found. Run 'make sniff' to fix."
    exit 1
fi

Implementation Patterns

Workflows

1. Daily Development

  • Spot-check files:
    vendor/bin/phpcs app/Http/Controllers/UserController.php
    
  • Fix autofixable issues:
    vendor/bin/phpcs --standard=vendor/flyeralarm/php-code-validator/ruleset.xml --fix .
    
  • IDE Integration (PHPStorm):
    1. Enable PHP Code Sniffer in Settings > Editor > Inspections > PHP.
    2. Set the coding standard to:
      vendor/flyeralarm/php-code-validator/ruleset.xml
      
    3. Configure on-save validation (optional).

2. CI/CD Pipeline (GitHub Actions Example)

name: PHP Code Style Check
on: [push, pull_request]

jobs:
  sniff:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: shivammathur/setup-php@v2
        with:
          php-version: '8.2'
      - run: composer install --dev
      - run: vendor/bin/phpcs --standard=vendor/flyeralarm/php-code-validator/ruleset.xml --report=checkstyle | tee results.xml
      - uses: actions/upload-artifact@v3
        if: failure()
        with:
          name: phpcs-results
          path: results.xml
  • Fail builds on violations by omitting --fix.
  • Cache dependencies (composer.lock) to speed up runs.

3. Custom Rule Extensions

Extend the ruleset for Laravel-specific needs (e.g., Eloquent query validation):

<!-- In phpcs.xml -->
<rule ref="vendor/flyeralarm/php-code-validator/ruleset.xml"/>
<rule ref="Custom/Laravel/QuerySniff">
    <properties>
        <property name="allowedMethods" value="where,orderBy,select"/>
    </properties>
</rule>
  • Create a custom sniff (PHP_CodeSniffer class) in app/CodeSniffer/Custom/Laravel/QuerySniff.php:
    <?php
    class Custom_Laravel_QuerySniff implements PHP_CodeSniffer_Rules_Sniff {
        public function register() {
            return array(
                T_STRING => $this,
            );
        }
    
        public function process(Tokens $tokens, $position) {
            if ($tokens[$position]['code'] === T_STRING &&
                $tokens[$position]['content'] === 'query' &&
                $this->hasUnallowedMethod($tokens, $position)) {
                return new PHP_CodeSniffer_FixableError(
                    'Unallowed Eloquent query method detected.',
                    $position,
                    $this->correctFix($tokens, $position)
                );
            }
        }
    }
    

4. Partial Validation

Exclude vendor files or specific directories:

<!-- In phpcs.xml -->
<exclude-pattern>./vendor/</exclude-pattern>
<exclude-pattern>./storage/</exclude-pattern>
<exclude-pattern>./tests/Feature/IntegrationTest.php</exclude-pattern>

Integration Tips

Laravel-Specific Adjustments

  1. Override Naming Rules:
    • Laravel’s *RepositoryInterface violates the "no Interface suffix" rule. Workaround:
      <rule ref="vendor/flyeralarm/php-code-validator/ruleset.xml">
          <exclude name="FLYERALARM.Naming.NoInterfaceSuffix"/>
      </rule>
      
  2. Test Files:
    • Use @expectedExceptionMessage for Laravel’s expectExceptionMessage:
      // tests/Unit/UserTest.php
      public function test_create_user() {
          $this->expectException(ValidationException::class);
          $this->expectExceptionMessage('The email field is required.');
          // ...
      }
      
  3. Artisan Commands:
    • Add a custom command to run checks:
      // app/Console/Commands/CodeSniffCommand.php
      namespace App\Console\Commands;
      use Illuminate\Console\Command;
      class CodeSniffCommand extends Command {
          protected $signature = 'code:sniff {--fix : Auto-fix issues}';
          public function handle() {
              $command = 'vendor/bin/phpcs';
              if ($this->option('fix')) {
                  $command .= ' --fix';
              }
              $command .= ' --standard=vendor/flyeralarm/php-code-validator/ruleset.xml .';
              shell_exec($command);
          }
      }
      
    • Register in app/Console/Kernel.php:
      protected $commands = [
          Commands\CodeSniffCommand::class,
      ];
      

Performance Optimization

  • Cache results in CI:
    vendor/bin/phpcs --cache=./phpcs.cache --standard=vendor/flyeralarm/php-code-validator/ruleset.xml .
    
  • Parallelize checks (PHP_CodeSniffer 3.6+):
    vendor/bin/phpcs --parallel=4 .
    

Gotchas and Tips

Pitfalls

  1. False Positives in Laravel:

    • Issue: Laravel’s RouteServiceProvider uses Route::group(), which may trigger "fully qualified class name" rules.
    • Fix: Exclude specific files or adjust the FullyQualifiedSniff:
      <rule ref="vendor/flyeralarm/php-code-validator/ruleset.xml">
          <exclude name="FLYERALARM.FullyQualified.FullyQualifiedClass"/>
      </rule>
      
    • Alternative: Use use statements at the top of files (Laravel’s convention).
  2. Yoda Conditions in Blade:

    • Issue: Blade templates may use {{ 1 === $count }} (Yoda), which violates the rule.
    • Fix: Disable the rule for Blade files:
      <file>./resources/views/</file>
      <rule ref="vendor/flyeralarm/php-code-validator/ruleset.xml">
          <exclude name="FLYERALARM.ControlStructures.YodaCondition"/>
      </rule>
      
  3. Exception Messages:

    • Issue: Laravel’s ValidationException messages may contain dots (e.g., "The email must be valid.").
    • Fix: Override the rule or document exceptions in phpcs.xml:
      <config name="exception_message_allowed_chars" value=".,!?"/>
      
  4. PHPStan/Psalm Conflicts:

    • Issue: The package removed ReturnTypeSniff (too restrictive). Use PHPStan for type checks instead.
    • Fix: Install PHPStan separately:
      composer require --dev phpstan/phpstan
      
      Configure in phpstan.neon:
      includes:
          - vendor/flyeralarm/php-code-validator/phpstan.neon
      
  5. Windows Line Endings:

    • Issue: make sniff may fail on Windows due to line endings.
    • Fix: Normalize line endings in CI:
      dos2unix app/**/*.php tests/**/*.php
      vendor/bin/phpcs .
      

Debugging

  1. Verbose Output:
    vendor/bin/phpcs -v --standard=vendor/flyeralarm/php-code-validator/ruleset.xml .
    
  2. Rule-Specific Debugging:
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