Enforce code standards with composer, git hooks, and phpcs

April 14, 2014
By Chris Saylor (cjsaylor)

Maintaining code quality on projects where there are many developers contributing
is a tough assignment. How many times have you tried to contribute to an open-source project
only to find the maintainer rejecting your pull request on the grounds of some invisible coding
standard? How many times as a maintainer of an open-source project (or internal) have you had a
hard time reading code because there were careless tabs/spaces mixed, if statements with no brackets,
and other such things. Luckily there are tools that can assist maintainers. In this post,
I’ll be going over how to use composer, git hooks, and phpcs to
enforce code quality rules.

There are a couple of things to keep in mind. First, you want this process to be as simple as possible.
Secondly, you want it to be easy to run when necessary. Finally, you want
it to be universally accepted as part of your contribution procedure.

There Is No Catch

What if I told you that it could be done without the developer even knowing it’s happening?

Most modern PHP projects use composer as their dependency manager. Before you can make anything work, you need to run composer install.
This is where the magic happens.

Phpcs Dependency

First, we need a development dependency specified to install phpcs. It looks something like this:

{
"require-dev": [
"squizlabs/php_codesniffer": "2.0.*@dev"
]
}

Install Scripts

Composer has a handy schema entry called scripts. It supports a script hook
post-install-cmd. We will use this to install a git pre-commit hook. Adding to
our example above: