Combine power of PHP_CodeSniffer and PHP-CS-Fixer in 3 lines
Both powerful tools dealing with coding standards with huge communities behind them. Can you imagine using them both and actually enjoy it? Today I will show you how.
Right to The Answer
Let's say we want to check arrays.
We add first checker that requires long
checkers: - PHP_CodeSniffer\Standards\Generic\Sniffs\Arrays\DisallowShortArraySyntaxSniff
Great start. Then we want to check for trailing commas, so every line has them.
So add one more checker:
checkers: - PHP_CodeSniffer\Standards\Generic\Sniffs\Arrays\DisallowShortArraySyntaxSniff - PhpCsFixer\Fixer\ArrayNotation\TrailingCommaInMultilineArrayFixer
Great job! You have just combined PHP_CodeSniffer and PHP-CS-Fixer in 3 lines.
With a help of EasyCodingStandard. Now, when title promise is fulfilled, I will show how to install it, run it and how nice and clear reports it generates.
How to add EasyCodingStandard in 3 steps
1. Install Package
composer require --dev symplify/easy-coding-standard
easy-coding-standard.neon and Configure
easy-coding-standard.neon file in your project and desired checkers.
checkers: # arrays - PHP_CodeSniffer\Standards\Generic\Sniffs\Arrays\DisallowShortArraySyntaxSniff - PhpCsFixer\Fixer\ArrayNotation\TrailingCommaInMultilineArrayFixer
You can add a comment to groups, so everyone can easily orientate when there are more checkers.
Be Lazy with NEON
Do you use PHPStorm? If so, you can use NEON Plugin. It allows you one amazing thing:
It autocompletes class names!
No more looking to documentation, what string matches what sniff or fixer, if there are any checkers for arrays or debugging typos.
NEON file format is very similar to YAML.
To install NEON PHPStorm plugin just: find everywhere → type "Plugins" → pick "Browse repositories..." in the bottom → type "NEON" and install it.
3. Run it & Fix it
vendor/bin/easy-coding-standard check src # ... vendor/bin/easy-coding-standard check src --fix
Well, unless you like videos...
Watch 🕑 11 min Intro Talks from Dresden PHP Meetup
I spoke about ECS last week in Dresden. If you have 11 minutes and you want to know more about it, go watch it here it here.
That's all for short intro of this tool. I'll post more articles about how to use it, about fast caching or how to write own checkers - both sniffs and fixers.
Thank you for any feedback. Here or in the issues.