Simple forced linting in PHP projects (Husky + Git hooks + Laravel Pint)
Sometimes a team needs to follow a consistent style of code design. How to achieve this as easily as possible on a PHP project?
As soon as the team becomes large enough, there is an immediate need to apply forceful linting to the team to observe a common style and prevent conflicts. How to achieve this on a PHP project? Husky, Git hooks, and Laravel Pint will help us with that
Let's get started
Let's imagine that we are working in a completely new directory and just creating a project
№0. Create an empty project
Run this:
cd ~/
mkdir linting_example
cd linting_example
№1. Initialise a Git repository
Run this:
git init
№2. Husky
Run this:
npm init -y #you can skip that, but we assume that we have really fresh installation
npx husky-init && npm install
This command will create the first pre-commit hook in the ./linting_example/.husky/pre-commit
directory
(You might want to check out this guide if you are facing some problems)
№3. Laravel Pint
There are many ways to do code linting, there are many style guides, but believe me the easiest, fastest and most satisfying way is Laravel Pint. You will have zero configuration tool that will perform linting quickly and according to modern, clear rules.
Run this:
composer require laravel/pint --dev
№4. Command for hook
Now we will slightly modify the command that is executed before a commit.
To do this, change the contents of ./linting_example/.husky/pre-commit to look like this
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
./vendor/bin/pint --preset psr12 ./
git add $(git diff-index --cached --name-only --diff-filter=ACMR HEAD | grep '\.php$') # this command adds ONLY those files that were in the git cache before the commit
This command will lint files and add to commit only those files that were in the git cache (the git add command was executed on those files).
If you are using docker, the first command can be like this
docker exec -i php-container -v $(pwd):/linting_example -w /linting_example bash -c 'php -dxdebug.mode=off ./vendor/bin/pint --preset psr12 ./'
Let’s test it!
Now let's see how our linting works with a class that doesn't match PSR-12. Watch a short video of a linting demonstration below
Works great, doesn't it? 😎
It helps with work every day!
Subscribe, leave comments to see new tips and articles!