Reading other people's code is not an uncommon task, and this becomes difficult when each person has a different habit of writing code, making it difficult for reading comprehension, as well as modifying and developing later. For that reason, rules need to be followed to define code standards and improve the readability of the source code.

Coding Standard

Coding Standard is a set of rules specifying the coding of a program that a programmer must follow when participating in the project developing that program. Depending on the project, there will be different standards.

What is the PHP Code Sniffer?

- PHP Code Sniffer (also known as phpcs) is an essential tool for programmers to check coding conventions, to ensure your code is clean, code compliant with coding conventions.

- PHP Code Sniffer includes 2 scripts:

  • The phpcs script is the main script that encodes PHP, Javascript, and CSS files to detect coding convention violations. 
  • Phpcbf script to automatically fix parts of code that violate the coding convention standards.

Install Magento 2 coding standard

Install into Magento directory

Go to your Magento root directory, install using composer

composer require --dev magento/magento-coding-standard

Standalone install

Download the latest release from https://github.com/magento/magento-coding-standard/releases

After the download has completed, runĀ composer install from the unarchived directory

Usage

Go to the coding standard directory (under vendor/ if installed alongside a Magento installation)

bin/phpcs [path to Magento module] --standard=Magento2 --severity=10
  • phpcs: PHP coding standardĀ 
  • [path to Magento module]: replace with actual path to your module
  • --standard=Magento2: check with Magento 2 standards
  • --severity=10: check for issues with severity 10. All modules submitted to Magento Marketplace are automatically tested against this level of severity. Other severity levels are as follow:

If you choose a lower severity level, all issues at this level and higher levels will be checked.

In case your codes violate any coding standards, a message will appear as shown below: 

Each issue will be displayed with the full path, line number, and error message.

Some issues can be fixed automatically using phpcbf (PHP code beautifier and fixer), simply run the following command:

bin/phpcbf [path to Magento module] --standard=Magento2

We at Magenest hope that you can find the answers to your questions in our blog today. If you still have something unclear, please drop a comment down in this blog.