PHP Coding Standards fixer with git commit
PHP CS Fixer is an awesome tool for fixing coding standard violations in PHP code as explained here : PHP Code Standards Fixer
This article is about configuring PHP Coding Standards fixer to be run with git commit.
Configuration :
- Create a configuration file (.php_cs.dist) in the root directory of your project as explained here
2. Create an empty pre-commit file in .githooks folder => This is helpful when working in a team
3. Paste the following lines to the pre-commit file :
Replace vendor/bin/php-cs-fixer by the path to php-cs-fixer script in case isn’t installed by composer
To make sure the fixer scans only modified files (and not all the app) we need to fetch all files added to the list to be committed, and only existing files (ignore removed)
git diff : Show difference between HEAD and current workspace.
- — cached : returns only added files with git add.
- — name-only : returns only files names
- — diff-filter : filters files with [A for Added, C for Copied, M for Modified, R for Renamed]
4. Replace the default git hooks path by the created folder .githooks by executing :
$ git config core.hooksPath .githooks
Or add it to the Makefile if exists :
Anyone working on the project needs to execute this command (or run make config) in his workspace.
Example
- Create an IndexController and write some dirty code.
2. Add the file to the commit list
3. Commit
4. The file is fixed automatically