In one of my recent projects, I wanted to set up a process where my code is checked for code formatting and unit tests are executed automatically before the code is pushed to the git repository. We have worked with Gitlab pipelines where code is validated against multiple php versions and it will automatically notify if any code commit is breaking anything.
Yes, if we run phpunit before every commit, this problem will not happen. Also, I am a very big fan of clean and well formatted code. And, it would be very nice if I can run the php-cs-fix command as well before code commit. However, sometimes I do forget. And that’s why automation is important.
Husky is one package which allows us to work with Githooks. We get the ability to act on different Git hooks and then take actions accordingly. And, lint-staged is one package which will let you only run the formatting code on the files which have changed instead of scanning the entire code folder.
So, how do we set this up? Let’s start our code editor and get into action
Step 1: We would need to install two npm packages “husky” and “lint-staged”. These can be your dev dependencies.
Step 2: Inside your package.json you have two configuration blocks. One for husky where we will hook into two events “pre-commit” and “pre-push”. And the second one is lint-staged where we will look for all php files and run our php-cs-fixer on them.
Here is how the final package.json file will look with those two blocks
Once this is done, we just need to ensure that we have the composer package “friendsofphp/php-cs-fixer” as part of our dev dependency.
If everything is done properly, you should see an output similar to this when you do a git commit and git push. Typically, I run the command now in one shot like:
git add . && git commit -m "My message goes here" && git push
And one by one, the code fix is done as part of the commit command and phpunit is executed as part of git push.
If you like to see this in a video, you can refer to this video that I have uploaded on Youtube. The set up is a little different because I have the react app client app and server api code in the same repository. However, the set follows the same structure.
Credits: To learn about this and set up, I have followed this article a lot Sebastian De Deyne apart from the module documentation on npm.
Hope you like it.