e-Zest members share technology ideas to foster digital transformation.

Code validations using static-review library in Magento

Written by Shubh Sharma | Oct 19, 2018 5:58:00 AM
Introduction:

Magento2 comes up with some advance tools and plugins, which are really useful for developers to track some common errors during development; I am going to introduce a small tutorial, which helps developers to validate PHP scripts before committing code to Git branch.

Below are some of the validations that can be validated using the described tutorial:

  • LineEndingsReview
  • PhpLeadingLineReview
  • NoCommitTagReview
  • PhpLintReview
  • ComposerLintReview
  • PhpCodeSnifferReview
  • ComposerSecurityReview
Requirements:

  • Git
  • magento2 (2.2.5)
  • sjparkinson/static-review (library)
Installing library sjparkinson/static-review:

To install it in your project, run composer require sjparkinson/static-review in the root of your magento2 installation directory

Command: composer require sjparkinson/static-review


A Working Example:

  • First, we need to identify the action/observer which requires PHP script validation, So in our example we will validate and run phpunit whenever a developer committed the code in any branch from his local machine
  • Action/Observer can register using Git hooks, If you’ve been using Git for more than a short length of time. you’ll hopefully have heard of Git hooks. There are hooks for pre- and post-commit, pre- and post-update, pre-push, pre-rebase, and so on. Using Static Review library, you can write Git hooks with PHP.
  • To register a hook in Git using Static Review tool follow these steps:
STEP1:

Command: php vendor/bin/static-review.php


STEP2:

Command: php vendor/bin/static-review.php help hook:install


STEP3:


Command: php vendor/bin/static-review.php hook:install -f vendor/sjparkinson/static-review/hooks/static-review-pre-commit.php .git/hooks/pre-commit


  • Hook has been registered successfully
  • Commit your changes using Git commit command ‘git commit -m “your message” ’. This command automatically scans your changes against validations and displays the result on the screen (refer below screenshot)


There are many more ways to utilize static review library, we can create our own review rules based on the coding standards, and hopefully this small tutorial will help simplify the life of the developer.