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 Conventions Laravel Package

drupol/php-conventions

Opinionated PHP conventions toolkit with presets for code style, static analysis, and QA tooling. Helps standardize projects quickly by providing shared configuration and automation-friendly defaults for common PHP workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require drupol/php-conventions
    

    No publisher or service provider is required—it’s a standalone utility.

  2. First Use Case Validate a PHP file against PSR-12 conventions:

    use Drupol\PhpConventions\Validator;
    
    $validator = new Validator();
    $result = $validator->validateFile('/path/to/YourClass.php');
    
    if ($result->isValid()) {
        echo "File adheres to PSR-12 conventions!";
    } else {
        foreach ($result->getErrors() as $error) {
            echo "Line {$error['line']}: {$error['message']}\n";
        }
    }
    
  3. Where to Look First

    • Validator Class: Core entry point for validation.
    • Rules Directory: src/Rules/ contains individual PSR-12 checks (e.g., ClassDeclarationRule, MethodDeclarationRule).
    • Tests: tests/ demonstrates usage patterns and edge cases.

Implementation Patterns

Validation Workflows

  1. File Validation Validate a single file:

    $validator = new Validator();
    $result = $validator->validateFile('app/Models/User.php');
    
  2. Directory Validation Recursively validate all .php files in a directory:

    $result = $validator->validateDirectory('app');
    
  3. Custom Rule Integration Extend validation with custom rules (e.g., enforce returnType for methods):

    use Drupol\PhpConventions\Rules\AbstractRule;
    
    class CustomReturnTypeRule extends AbstractRule {
        public function check($node) {
            if (!$node->returnType && $node->type === 'method') {
                return $this->fail('Method must declare a return type.');
            }
            return true;
        }
    }
    
    $validator = new Validator();
    $validator->addRule(new CustomReturnTypeRule());
    
  4. Integration with Laravel Use in a Service Provider or Artisan Command for pre-commit hooks:

    // app/Providers/AppServiceProvider.php
    use Drupol\PhpConventions\Validator;
    
    public function boot() {
        $validator = new Validator();
        $validator->validateDirectory(base_path('app'));
    }
    
  5. CI/CD Pipeline Fail builds on convention violations (e.g., GitHub Actions):

    - name: Run PHP Conventions Check
      run: |
        php vendor/bin/php-conventions validate app --fail-on-error
    

Common Use Cases

Use Case Implementation
Pre-commit Hook Run via php artisan conventions:check
CI Linting Fail pipeline if violations exist
IDE Integration Use as a background checker (e.g., PHPStorm plugin)
Code Reviews Automate PSR-12 checks in PR templates

Gotchas and Tips

Pitfalls

  1. False Positives

    • Issue: Legacy code or framework-specific patterns (e.g., Laravel’s fillable) may trigger unnecessary errors.
    • Fix: Whitelist files/directories or extend rules to ignore specific cases:
      $validator->ignoreFiles(['app/Helpers/legacy_helper.php']);
      
  2. Performance

    • Issue: Validating large codebases (e.g., vendor/) can be slow.
    • Fix: Exclude vendor/ and focus on app/:
      $validator->validateDirectory(app_path());
      
  3. Rule Conflicts

    • Issue: Custom rules may override default PSR-12 checks.
    • Fix: Prioritize rules explicitly:
      $validator->setPriority([new CustomRule(), new ClassDeclarationRule()]);
      
  4. PhpParser Dependency

    • Issue: Requires php-parser (installed automatically via Composer).
    • Fix: Ensure ext-dom is enabled in php.ini for AST parsing.

Debugging Tips

  1. Verbose Output Enable detailed error messages:

    $validator->setVerbose(true);
    
  2. Log Violations Save results to a file for auditing:

    $result = $validator->validateDirectory(app_path());
    file_put_contents(storage_path('logs/conventions.log'), $result->toString());
    
  3. Test Rules Isolated Unit test custom rules:

    $this->assertTrue((new CustomRule())->check($astNode));
    

Extension Points

  1. Custom Rules Extend AbstractRule to add new checks (e.g., enforce @throws annotations):

    class ThrowsAnnotationRule extends AbstractRule {
        public function check($node) {
            if ($node->type === 'method' && empty($node->docs)) {
                return $this->fail('Method must have PHPDoc.');
            }
            return true;
        }
    }
    
  2. Reporters Implement ReporterInterface to format output (e.g., JSON for APIs):

    class JsonReporter implements ReporterInterface {
        public function report(Result $result) {
            return json_encode($result->getErrors());
        }
    }
    
  3. Configuration Load rules from a config file (e.g., conventions.php):

    $validator = new Validator();
    $validator->loadRulesFromConfig(config('conventions.rules'));
    

Pro Tips

  • Combine with php-cs-fixer: Use this package for static analysis and php-cs-fixer for automated fixes.
  • Laravel Artisan Command: Wrap the validator in a command for CLI access:
    // app/Console/Commands/ConventionsCheck.php
    public function handle() {
        $result = (new Validator())->validateDirectory(app_path());
        if (!$result->isValid()) {
            $this->error($result->toString());
            exit(1);
        }
    }
    
  • Git Hooks: Integrate with pre-commit via:
    composer require --dev laravel-zero/framework
    vendor/bin/laravel new ConventionsCheckCommand
    
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