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

Phpstan Rules Laravel Package

solido/phpstan-rules

Custom PHPStan ruleset for Solido-based projects. Adds extra static analysis for enhanced DTOs with simple phpstan.neon config to declare DTO namespaces and excluded interfaces, helping catch type and structure issues across your application.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

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

    composer require --dev solido/phpstan-rules
    

    Ensure phpstan/phpstan is also installed (required).

  2. Configure PHPStan Update your phpstan.neon configuration file (typically in the project root) to include Solido-specific rules:

    includes:
        - vendor/solido/phpstan-rules/extension.neon
    
    parameters:
        solido:
            dto_namespaces:
                - App\DTO
                - App\Models\DTOs
            excluded_interfaces:
                - App\DTO\NonDTOInterface
    
  3. Run PHPStan Execute PHPStan with the new rules to analyze your codebase:

    vendor/bin/phpstan analyse src --level=5
    

    Focus on identifying DTO-related issues, such as invalid property access or type mismatches.


Implementation Patterns

Usage Patterns

  1. DTO Validation Workflow

    • Enforce DTO Instantiation Rules: Ensure DTOs are instantiated correctly (e.g., via factory methods or constructors) by leveraging the solido.dto.constructorUsage rule.
    • Property Access Validation: Use the solido.dto.propertyAccess rule to validate that only allowed properties are accessed on DTO objects.
  2. Type Safety Enforcement

    • Type Mismatch Detection: The solido.dto.typeMismatch rule helps catch type inconsistencies in DTO properties, ensuring that properties are assigned values of the correct type.
    • Immutable DTO Checks: If your project enforces immutability for DTOs, configure PHPStan to flag any attempts to modify DTO properties after creation.
  3. Custom Rule Integration

    • Extend Existing Rules: Create custom extensions in your extension.neon file to tailor the rules to your project’s specific needs:
      services:
          - Solido\PhpStanRules\Rules\DtoPropertyAccessRule
          - Solido\PhpStanRules\Rules\DtoTypeMismatchRule
      
  4. CI/CD Pipeline Integration

    • Git Hooks: Integrate PHPStan into your Git pre-commit or pre-push hooks to catch issues early in the development cycle.
    • CI/CD Workflows: Add PHPStan to your CI pipeline (e.g., GitHub Actions, GitLab CI) to ensure code quality before merging:
      # Example GitHub Actions workflow
      name: PHPStan Analysis
      on: [push, pull_request]
      jobs:
        phpstan:
          runs-on: ubuntu-latest
          steps:
            - uses: actions/checkout@v4
            - run: composer install
            - run: vendor/bin/phpstan analyse --level=5
      
  5. Laravel-Specific Patterns

    • DTOs in API Responses: Use the rules to validate DTOs used in API responses, ensuring they adhere to your project’s data contracts.
    • Form Request Validation: Validate that DTOs used in Laravel Form Requests match the expected structure and types.

Integration Tips

  1. Gradual Adoption

    • Start by running PHPStan with a lower severity level (e.g., --level=3) to identify issues without blocking development. Gradually increase the severity level as your team becomes more comfortable with the rules.
  2. Team Onboarding

    • Document the new rules and their purpose for your team. Provide examples of common violations and how to fix them.
    • Conduct a workshop or training session to ensure everyone understands how to use and interpret the PHPStan output.
  3. Custom Suppression

    • Use PHPStan’s suppression comments to temporarily ignore specific rule violations while you address them:
      // phpcs:ignore solido.dto.propertyAccess
      $dto->nonExistentProperty;
      
  4. Rule Prioritization

    • Focus on critical rules first (e.g., type mismatches, invalid property access) and address less critical issues (e.g., style violations) later.

Gotchas and Tips

Pitfalls

  1. Incorrect Namespace Configuration

    • Issue: If dto_namespaces in phpstan.neon is incomplete or incorrect, the rules may not apply to all DTOs, leading to missed violations.
    • Fix: Double-check that all DTO namespaces are included. Use wildcards cautiously (e.g., App\DTO\*), as they can lead to unintended matches.
  2. False Positives

    • Issue: Rules may incorrectly flag legitimate dynamic property access, such as when using magic methods like __get() or __set().
    • Fix: Exclude specific interfaces or methods using the excluded_interfaces parameter or suppress the rule for specific lines of code.
  3. Performance Issues

    • Issue: Running PHPStan with strict Solido rules can significantly slow down analysis, especially for large codebases.
    • Fix: Limit the scope of analysis to critical paths or increase memory limits:
      vendor/bin/phpstan analyse src --memory-limit=1G
      
  4. Rule Conflicts

    • Issue: Overlapping rules (e.g., PHPStan’s native PropertyTypeMismatch vs. solido.dto.typeMismatch) can lead to redundant or conflicting error messages.
    • Fix: Prioritize Solido-specific rules by ordering them appropriately in your extension.neon file or disabling conflicting native rules.
  5. Outdated Rules

    • Issue: If Solido’s DTO conventions evolve, existing rules may become outdated or ineffective.
    • Fix: Monitor Solido’s release notes and update your rules configuration as needed. Consider contributing to the package if you encounter issues.

Debugging Tips

  1. Enable Debug Mode

    • Use PHPStan’s debug mode to get detailed information about rule application:
      vendor/bin/phpstan analyse --debug
      
  2. Generate Reports

    • Generate a report to identify patterns in violations:
      vendor/bin/phpstan analyse --generate-report=report.html
      
  3. Isolate Issues

    • Run PHPStan on specific directories or files to isolate issues:
      vendor/bin/phpstan analyse src/DTO --level=5
      

Extension Points

  1. Custom Rules

    • Extend the package by creating custom rules for your project’s specific needs. For example, you might want to add rules for validating DTOs used in Laravel’s Eloquent models or API resources.
  2. Rule Configuration

    • Fine-tune rule behavior by adjusting parameters in phpstan.neon. For example, you can exclude specific interfaces or adjust the severity level of certain rules.
  3. Integration with Other Tools

    • Combine PHPStan with other static analysis tools (e.g., Psalm, PHPMD) to get a more comprehensive view of your codebase’s quality.
  4. Automated Fixes

    • Use PHPStan’s --fix option (if available) or create custom scripts to automatically fix common issues, such as type mismatches or invalid property access.

Laravel-Specific Tips

  1. DTOs in API Resources

    • Use the rules to validate DTOs used in Laravel’s API Resources, ensuring they match the expected structure and types for your API responses.
  2. Form Request Validation

    • Validate that DTOs used in Laravel Form Requests adhere to your project’s data contracts, reducing runtime errors related to invalid data.
  3. Service Container Binding

    • Ensure that DTOs bound to the Laravel service container are correctly typed and instantiated, leveraging the solido.dto.constructorUsage rule.
  4. Testing Integration

    • Integrate PHPStan into your testing workflow to catch DTO-related issues early in the development cycle, especially when writing unit or feature tests.
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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