Git 提交 PHP 代码风格检测配置

    composer.json 文件

    1. {
    2. "require": {
    3. "friendsofphp/php-cs-fixer": "^2.16",
    4. "brainmaestro/composer-git-hooks": "^2.8"
    5. },
    6. "extra": {
    7. "hooks": {
    8. "pre-commit": [
    9. "composer check-style"
    10. ],
    11. "post-merge": "composer install"
    12. }
    13. },
    14. "scripts": {
    15. "post-update-cmd": [
    16. "cghooks update"
    17. ],
    18. "post-install-cmd": [
    19. "cghooks add --ignore-lock",
    20. "cghooks update"
    21. ],
    22. "cghooks": "vendor/bin/cghooks",
    23. "check-style": "php-cs-fixer fix --using-cache=no --diff --config=.php_cs --dry-run --ansi",
    24. "fix-style": "php-cs-fixer fix --using-cache=no --config=.php_cs --ansi"
    25. },
    26. "scripts-descriptions": {
    27. "check-style": "Run style checks (only dry run - no fixing!).",
    28. "fix-style": "Run style checks and fix violations."
    29. }
    30. }

    .php_cs 文件

    1. <?php
    2. return PhpCsFixer\Config::create()
    3. ->setRules([
    4. '@PSR2' => true,
    5. 'binary_operator_spaces' => true,
    6. 'blank_line_after_opening_tag' => true,
    7. 'compact_nullable_typehint' => true,
    8. 'declare_equal_normalize' => true,
    9. 'lowercase_cast' => true,
    10. 'lowercase_static_reference' => true,
    11. 'new_with_braces' => true,
    12. 'no_blank_lines_after_class_opening' => true,
    13. 'no_leading_import_slash' => true,
    14. 'no_whitespace_in_blank_line' => true,
    15. 'ordered_class_elements' => [
    16. 'order' => [
    17. 'use_trait',
    18. ],
    19. ],
    20. 'ordered_imports' => [
    21. 'imports_order' => [
    22. 'class',
    23. 'function',
    24. 'const',
    25. ],
    26. 'sort_algorithm' => 'none',
    27. ],
    28. 'return_type_declaration' => true,
    29. 'short_scalar_cast' => true,
    30. 'single_blank_line_before_namespace' => true,
    31. 'single_trait_insert_per_statement' => true,
    32. 'ternary_operator_spaces' => true,
    33. 'unary_operator_spaces' => true,
    34. 'visibility_required' => [
    35. 'elements' => [
    36. 'const',
    37. 'method',
    38. 'property',
    39. ],
    40. ],
    41. ])
    42. ->setFinder(
    43. PhpCsFixer\Finder::create()
    44. ->exclude('vendor')//排除的目录
    45. ->in([__DIR__.'/app/'])//检测的目录,支持多个目录
    46. )
    47. ;