PHP Coding Standards fixer with git commit

Youssef Benhssaien
2 min readJul 19, 2020

--

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 :

  1. 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

.githooks

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.

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 :

Makefile

Anyone working on the project needs to execute this command (or run make config) in his workspace.

Example

  1. Create an IndexController and write some dirty code.
IndexController

2. Add the file to the commit list

3. Commit

4. The file is fixed automatically

That’s it … Happy coding😊

--

--