Using git hooks to enforce PSR-2 on modified code

Sérgio Serra
codeburst
Published in
2 min readMay 14, 2018

--

You probably noticed the nuance on the article title: “modified code”.

Recently I decided to use git hooks to guarantee that all code committed on a project is PSR-2 compliant. Of course I started googling around and found some solutions to easily do this.

The problem was that all solutions I found were based on full file analysis. This is not a problem if you have a recent codebase or a new codebase were you can enforce the style from the beginning.

But if you have an application with years of development where you want to start to enforce code styling this is not a solution. Because it would force full file compliance and this may involve modify large amounts of code.

There are also solutions that automatically format the files with PSR-2 before commit. But I don’t want to lose line authorship because git blame besides the *evil* opportunity to quickly blame someone for a bug, has also the true advantage of contextualize the when of a change and who can help with it if something seems to be missing.

But then I found coverageChecker that seemed to do exactly what I needed: check standards only on modified code.

So based on their documentation I created a pre-commit hook that can be found here.

It’s necessary to add some composer dependencies included on composer.json file also shared on gist.

The hook also validates syntax using php -l so it is necessary to have php cli installed.

How it works?

The hook performs two actions: searches for syntax errors on code and then validates the style. All checks are done only on staged modifications.

If a syntax error is found the commit is immediately aborted and no further tests are done.

If the problem is only with the style, the validation will continue. All problems found are outputted and the commit is finally aborted.

✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.

--

--

Over the years I have worn many different hats with technology at heart.