- How do I install php-collective/code-sniffer for a Laravel project?
- Run `composer require --dev php-collective/code-sniffer` to add it as a dev dependency. Then create a `phpcs.xml` file in your project root referencing the standard (e.g., `<rule ref="vendor/php-collective/code-sniffer/PhpCollective/ruleset.xml"/>`).
- Does this package work with Laravel’s default PSR-2 setup?
- Yes, it extends PSR-2 with additional rules (including PSR-12) while maintaining compatibility. Laravel’s default `phpcs.xml` often references PSR-2, so this package can replace or supplement it seamlessly.
- What’s the difference between PhpCollective and PhpCollectiveStrict?
- PhpCollective enforces PSR-2/PSR-12 with extra conventions, while PhpCollectiveStrict adds stricter rules like type-hinting (e.g., `ParameterTypeHint`, `PropertyTypeHint`). Use Strict for modern PHP 8+ projects with typed properties.
- Can I auto-fix code style issues in Laravel?
- Yes, use `phpcbf` (auto-fixer) via Composer scripts (e.g., `composer cs-fix`). The package includes fixers for common violations like line breaks, indentation, and docblocks, reducing manual refactoring.
- Will this break existing Laravel codebases?
- Potentially, especially if using PhpCollectiveStrict. Run `phpcs --report=full` first to assess violations (e.g., short open tags, line length). Use `--ignore` in `phpcs.xml` or exclude problematic files temporarily.
- How do I integrate this into Laravel’s CI pipeline?
- Add a Composer script like `"cs-check": "phpcs -nps --standard=PhpCollective"` to your `composer.json`. Run it in CI (e.g., GitHub Actions) to block merges with style violations or log warnings.
- Does this support PHP 8.x features like typed properties?
- Yes, PhpCollectiveStrict includes rules for typed properties (e.g., `string $name`), constructor property promotion, and modern type-hinting, aligning with Laravel 9+/10+ and PHP 8.1+.
- Can I customize or override rules for my Laravel project?
- Absolutely. Extend the standard in `phpcs.xml` by adding `<config>` tags or overriding rules (e.g., `<rule ref="PhpCollective.WhiteSpace.LineLength" severity="0"/>`). Exclude directories with `<exclude-pattern>*/tests/*</exclude-pattern>`.
- How do I set up pre-commit hooks for code style checks?
- Use tools like Husky with a script like `npx husky add .husky/pre-commit "composer cs-check"`. This runs `phpcs` before commits, preventing style violations from being merged.
- Are there alternatives to php-collective/code-sniffer for Laravel?
- Yes, consider `laravel-shift/code-sniffer` (Laravel-specific rules) or `dealerdirect/phpcodesniffer-composer` (PSR-12 focused). However, PhpCollective offers a balanced mix of PSR compliance and Laravel-friendly conventions with auto-fix support.