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

worksome/coding-style

Worksome’s shared PHP coding style package. Generates ready-to-use configs for Easy Coding Standard (ECS), PHPStan, and Rector, extending PSR-12 with additional and customized rules. Install via Composer, generate stubs, and run via composer scripts.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require --dev worksome/coding-style
    composer generate-coding-style-stubs
    

    This generates the required config files (ecs.php, phpstan.neon, rector.php) in your project root.

  2. Add Scripts to composer.json:

    "scripts": {
        "ecs": "vendor/bin/ecs",
        "ecs:fix": "vendor/bin/ecs --fix",
        "phpstan": "vendor/bin/phpstan analyse",
        "rector": "vendor/bin/rector process --dry-run --ansi",
        "rector:fix": "vendor/bin/rector process --ansi"
    }
    
  3. First Use Case: Run a dry check on your codebase:

    composer ecs
    composer phpstan
    composer rector
    

    Use --fix flags to auto-correct issues where possible:

    composer ecs:fix
    composer rector:fix
    

Implementation Patterns

Daily Workflow Integration

  1. Pre-Commit Hooks: Integrate with tools like Husky or Git Hooks to run composer ecs and composer phpstan before commits:

    composer ecs --dry-run
    composer phpstan analyse --level=5
    

    Fail the commit if violations are found.

  2. CI/CD Pipeline: Add checks to your CI (e.g., GitHub Actions, GitLab CI) to enforce coding standards:

    # Example GitHub Actions step
    - name: Run ECS and PHPStan
      run: |
        composer ecs
        composer phpstan analyse --level=5
    
  3. Onboarding New Developers: Document the coding style in your CONTRIBUTING.md and include a one-time setup guide:

    ## Setup Coding Standards
    ```bash
    composer require --dev worksome/coding-style
    composer generate-coding-style-stubs
    composer ecs:fix  # Auto-fix common issues
    
    
    
  4. Project-Specific Customization: Override default rules by extending the generated configs:

    // ecs.php
    return [
        'rules' => [
            'Worksome\CodingStyle\Sniffs\Laravel\DisallowEnvUsageSniff' => null, // Disable for specific files
            'SlevomatCodingStandard\Sniffs\TypeHints\ParameterTypeHintSpacingSniff' => true,
        ],
        'paths' => [
            __DIR__.'/src',
            // Exclude specific directories
            !__DIR__.'/tests',
        ],
    ];
    
  5. Leveraging Rector for Refactoring: Use Rector for automated refactoring (e.g., upgrading PHP versions, migrating syntax):

    composer rector --ansi --dry-run  # Preview changes
    composer rector:fix              # Apply changes
    

Gotchas and Tips

Pitfalls

  1. Strict PHPStan Rules:

    • The worksome.disallowPhpunit rule blocks PHPUnit tests entirely. If your project uses PHPUnit, either:
      • Disable the rule in phpstan.neon:
        includes:
            - vendor/worksome/coding-style/phpstan/laravel.neon
        services:
            Worksome\CodingStyle\PHPStan\DisallowPHPUnitRule: ~
        
      • Migrate to Pest PHP.
  2. Artisan Command Naming:

    • The worksome.laravel.kebabCaseArtisanCommands rule enforces kebab-case for Artisan commands. Ensure your commands follow this convention:
      // ❌ Avoid
      php artisan make:auth
      
      // ✅ Prefer
      php artisan make:auth --kebab-case
      
  3. Factory Usage:

    • The DisallowHasFactorySniff rule requires factories to be called directly (e.g., User::factory() instead of $user->create() with HasFactory). Update your models and tests:
      // ❌ Avoid
      class User extends Model {
          use HasFactory;
      }
      
      // ✅ Prefer
      class User extends Model {}
      User::factory()->create();
      
  4. Blade Files Outside resources:

    • The DisallowBladeOutsideOfResourcesDirectorySniff will fail if .blade.php files exist elsewhere. Move them to resources/views/ or rename them.
  5. Environment Checks:

    • The worksome.laravel.disallowEnvironmentCheck rule discourages app()->environment() checks. Use driver-based configurations (e.g., config('services.stripe.enabled')) instead.
  6. Enum Case Naming:

    • Enums must use PascalCase for cases (e.g., Status::Active). Avoid snake_case or camelCase:
      // ❌ Avoid
      enum Status { ACTIVE, INACTIVE } // snake_case
      enum Status { active, inactive }  // camelCase
      
      // ✅ Prefer
      enum Status { Active, Inactive }
      
  7. Config File Naming:

    • Config files must use kebab-case (e.g., app-config.php). Rename existing files:
      mv config/app_config.php config/app-config.php
      

Debugging Tips

  1. Isolate Rule Violations: Run ECS/PHPStan on specific files to debug:

    composer ecs src/Models/User.php
    composer phpstan analyse src/Models/User.php
    
  2. Temporarily Disable Rules: Disable a rule in ecs.php or phpstan.neon to bypass it during debugging:

    // ecs.php
    return [
        'rules' => [
            'Worksome\CodingStyle\Sniffs\Laravel\DisallowEnvUsageSniff' => null,
        ],
    ];
    
  3. Understand Auto-Fix Limitations:

    • Not all rules support auto-fixing (e.g., custom sniffs like DisallowTodoCommentsSniff). Manually fix these or extend the package.
  4. Leverage --verbose: Run tools with verbose output for detailed error messages:

    composer ecs --verbose
    composer phpstan analyse --verbose
    
  5. Check for Deprecated Rules: If a rule fails unexpectedly, verify it hasn’t been deprecated or replaced in newer versions of the package.


Extension Points

  1. Custom Rules: Extend the package by adding your own rules. For example, create a custom PHPStan rule:

    // app/Rules/CustomRule.php
    namespace App\Rules;
    
    use PHPStan\Rules\Rule;
    use PHPStan\Rules\RuleErrorBuilder;
    
    class CustomRule implements Rule {
        public function getNodeType(): string {
            return 'PHPStan\Analyser\Node\Expr\MethodCall';
        }
    
        public function processNode(Node $node, Scope $scope) {
            if ($node->getMethodName() === 'oldWay') {
                return RuleErrorBuilder::message('Use newWay instead.')
                    ->build();
            }
        }
    }
    

    Include it in phpstan.neon:

    services:
        - App\Rules\CustomRule
    
  2. Override Configs: Copy the generated configs (ecs.php, phpstan.neon, rector.php) to config/ and customize them:

    cp ecs.php config/ecs.php
    

    Then update your composer.json scripts to point to the new location:

    "ecs": "vendor/bin/ecs --config=config/ecs.php"
    
  3. Integrate with IDE: Configure your IDE (e.g., PHPStorm, VSCode) to use the same coding standards:

  4. Partial Application: Apply the coding style selectively (e.g., only to new features):

    // ecs.php
    return [
        'paths' => [
            __DIR__.'/src/NewFeature',
        ],
    ];
    
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.
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
spatie/mailcoach-vapor