In this article we’re going to take a look at the main tool for validating PHP code and explain in detail how to check the code we write so we can contribute it to Icinga Web 2 and its modules.
First, let’s talk a little about coding conventions and what’s the standard for PHP projects.
Coding conventions are a set of guidelines for a specific programming language that recommend programming style, practices, and methods for each aspect of a program written in that language. These conventions usually cover file organization, indentation, comments, declarations, statements, white space, naming conventions, programming practices, programming principles, programming rules of thumb, architectural best practices, etc. These rules can change from project to project but the main goal is always to allow all the people working on a project to understand, maintain and extend the code written by others in a safe, easy and fast way. As you can understand, this is very important for Open Source projects.
Typically, every programming language has its own standard coding conventions, and PHP is no exception. The base standard defined by the main exponents in the PHP community is called PSR (PHP Standards Recommendations) and all the details can be found at this website.
PHP_CodeSniffer is a set of two PHP scripts, but in this article we will focus on the main one: phpcs. This utility tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard. It is a PHP script very easy to install and run. It can be also integrated to GIT hooks or in a CI environment. As a first step, we will learn to run it manually from a Linux CI.
The Icinga Web 2 projects largely follow the standard PSR coding conventions. There are just a few customizations that are defined in a PHP_CodeSniffer ruleset file shipped with the GitHub project.
Now that we know all the basic concepts, we can start with some manual steps to check if the code that we wrote follows the Icinga Web 2 coding guidelines or not!
wget https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar
wget https://raw.githubusercontent.com/Icinga/icingaweb2/master/phpcs.xml
wget https://raw.githubusercontent.com/Icinga/icingaweb2/master/icingaweb2.ruleset.xml
/usr/bin/php phpcs.phar --standard="phpcs.xml" "/tmp/php/IcingaWeb2TestClass.php"
/usr/bin/php phpcs.phar --standard="phpcs.xml" "/tmp/php/"
For more info about how to contribute to Icinga Web 2 check this link.