WordPress PHP CS Fixer

Looking to start my first pipeline. We do not need to deploy right way from live/production for our WordPress project but we do want to check and fix coding standards with PHP CS Fixer. Did find

php-cs-fixer:
  stage: linting
  image: registry.gitlab.com/pipeline-components/php-cs-fixer:latest
  script:
    - php-cs-fixer fix ./ --rules=@PSR12  --verbose --show-progress=dots
  rules:
    - exists:
        - setup.py    

at pipeline-components / php-cs-fixer · GitLab . But how would this work? Should I add it as .gitlab-ci.yml ? Also understood it looks in the app directory whereas we need it to check code in the current theme folder at wp-content/themes/theme and in some custom plugins.

Perhaps I should use something like

php-cs-fixer:
  stage: linting
  image: registry.gitlab.com/pipeline-components/php-cs-fixer:latest
  script:
    - changed_files=$(git diff --name-only $CI_COMMIT_BEFORE_SHA $CI_COMMIT_SHA | grep '\.php$' || true)
    - if [ -n "$changed_files" ]; then php-cs-fixer fix $changed_files --rules=@PSR12 --verbose --show-progress=dots; fi
  only:
    - merge_requests
    - master

and then perhaps tweak it to focus on the staging branch or just any merge request. We also use snake_case for methods and not methods like niceMethod so wonder how to do that. Any examples or suggestions would be great.

Guess I can extend with my own rules in .php-cs-fixer.dist.php and load those in with

rules:
    - exists:
        - .php-cs-fixer.dist.php

like we do with Github projects. And then load

<?php

/* https://gist.github.com/laravel-shift/cab527923ed2a109dda047b97d53c200 */

use PhpCsFixer\Config;
use PhpCsFixer\Finder;

$rules = [
    'array_syntax' => ['syntax' => 'short'],
     // Override the rule for method names
     'psr_method_casing' => false,
     // Add your custom rule for snake_case method names
     'method_argument_space' => [
         'on_multiline' => 'ensure_fully_multiline',
         'keep_multiple_spaces_after_comma' => false,
],

    'blank_line_after_namespace' => true,
...
$finder = Finder::create()
    ->in([
        __DIR__.'/wp-content/themes/theme-name',
        __DIR__.'wp-content/plugins/plugin-name',
        __DIR__.'wp-content/plugins/plugin-name-two',
    ])
    ->name('*.php')
    ->notName('*.twig.php')
    ->ignoreDotFiles(true)
    ->ignoreVCS(true);

return (new Config())
    ->setFinder($finder)
    ->setRules($rules)
    ->setRiskyAllowed(true)
    ->setUsingCache(true);

but adjusted to load directories we need. And as Gitlab only seems to call rules with that call I cannot add config. Just have not found examples as of yet.

The php-cs-fixer binary needs to know about the configuration. PHP-CS-Fixer/doc/usage.rst at master · PHP-CS-Fixer/PHP-CS-Fixer · GitHub highlights the --config parameter for custom rules. I’d suggest running the script locally, and once working, update the CI/CD configuration script section with the correct command call.

2 Likes