How to improve the quality of PHP code

Keywords: PHP xml github encoding

To be honest, PHP is under a lot of pressure in terms of code quality. By reading this series of articles, you'll learn how to improve the quality of your PHP code.

There are many reasons for this, but it's certainly not just the lack of proper testing tools for the PHP ecosystem. In this article, I want to show you a simple setup for basic quality testing of a project. I'm not going to go into any specific tools, but rather focus on setting up the test environment.

In this article, a demo code can be found on GitHub:  https://github.com/mkosiedowski/php-testing-demo  If you have any questions about the examples in this article, you can refer to them.

1 prerequisites

I assume you are familiar with PHP 7.1 syntax, you can use Composer and PSR-4 for automatic loading and psr-1 & psr-2 coding standards. In my example, the vendor binaries are installed in the. / bin directory.

2 build tools

We'll use different testing tools, so it's best to have something that can run them with a script. Phing provides us with an excellent solution to this problem. Similar to Apache Ant, phing can easily automate tasks using XML configuration. We can install it by running the following command:

 copy code

$ php composer.phar require --dev phing/phing

 

Then, create some basic build.xml files in the root directory of the project.

<?xml version="1.0" encoding="UTF-8"?><project name="MyProject" default="run"></project>

 

In the next steps, we will add some targets that are run by PHing.

3 static code analysis

The first thing you can do to improve the quality of your code is to set up a static code analyzer. They will read your error code without actually running it. It's like having a code review done by a robot in seconds. It's cool, isn't it?

4 code style

When written in the right style, your code is easier to maintain. Everyone knows (if you don't, you should at least start reading Robert C. Martin's "Clean Code"), but there are still many teams that have problems complying with the standards they have reached. We can use phpcs - PHP code to sniff the task of automation. Is it amazing.

We can install it by running the following command:

$ php composer.phar require --dev squizlabs/php_codesniffer

 

Then add a target to run it in build.xml. Your build.xml should now look like this:

<?xml version="1.0" encoding="UTF-8"?><project name="MyProject" default="run">    <target name="phpcs" description="Check code style with PHP_CodeSniffer">        <exec executable="bin/phpcs" passthru="true" checkreturn="true">            <arg line="--standard=PSR1,PSR2 -extensions=php src"/>        </exec>    </target>    <target name="run" depends="phpcs"/></project>

 

Now that you are ready to run. / bin/phing, phpc will automatically check if you have any errors on the PSR-1 and PSR-2 encoding standards.

Many frameworks, such as Symfony, define their own code style rules, which we can also check automatically. For example: if you are using the Symfony framework, please check the https://github.com/leaphub/phpcs-symfony2 Standard to learn how to use phpcs to check Symfony's standards.

Sample output of a malformed file:

MyProject > phpcs:  FILE: /home/maciej/workspace/php-testing/src/Domain/Price.php-------------------------------------------------------------------------FOUND 1 ERROR AFFECTING 1 LINE-------------------------------------------------------------------------28 | ERROR | Method name "Price::get_value" is not in camel caps format-------------------------------------------------------------------------Time: 67ms; Memory: 6Mb

 

During code review, no longer waste time checking coding standards, it will be implemented automatically from now on!

5 copy / paste detector

Duplicate code is not good, everyone knows. Sometimes we create code like this by mistake, and we never notice it. Sometimes we do it because we are lazy. It's best to have a tool that prompts you for this at build time. PHPCPD - PHP copy / paste detector.

Install it by running the following command:

$ php composer.phar require --dev sebastian/phpcpd

 

Then add the target to build.xml:

1 <target name="phpcpd" description="Generate pmd-cpd.xml using PHPCPD">    <exec executable="bin/phpcpd" passthru="true">        <arg line="src"/>    </exec></target>...<target name="run" depends="phpcs,phpcpd"/>

 

Sample output of repeated code checking running on the vendor Directory:

phpcpd 4.0.0 by Sebastian Bergmann. Found 74 clones with 2929 duplicated lines in 97 files: - /home/maciej/workspace/php-testing/vendor/phpspec/phpspec/src/PhpSpec/Matcher/TriggerMatcher.php:81-102     /home/maciej/workspace/php-testing/vendor/phpspec/phpspec/src/PhpSpec/Matcher/TriggerMatcher.php:114-135 - /home/maciej/workspace/php-testing/vendor/squizlabs/php_codesniffer/src/Reports/Full.php:81-114   /home/maciej/workspace/php-testing/vendor/squizlabs/php_codesniffer/src/Reports/Code.php:162-195 (...)

 

6 want real in-depth code analysis?

If you start your project from scratch, you should look at Phan - it's a very powerful code analyzer that will make your code beautiful. In https://github.com/phan/phan View on. Installation is very simple - just install the PHP ast extension (in Ubuntu, you can try to run sudo apt get install PHP AST) and run:

$ php composer.phar require --dev phan/phan

 

Then create a configuration file. phan/config.php with the following contents:

<?phpreturn [    'target_php_version' => '7.1',    'directory_list' => [        'src',        'vendor/symfony/console',    ],    "exclude_analysis_directory_list" => [        'vendor/'    ],]; 

 

Also create the phan target in the build.xml file:

<target name="phan" description="Check code with phan">   <exec executable="bin/phan" passthru="true" checkreturn="true"/></target>...<target name="run" depends="phpcs,phpcpd,phan"/>

 

Now, you can run your code analysis if you make a mistake (for example Declare the wrong phpdoc type for the class property), you should see the following message:

MyProject > phan: src/Domain/PriceComparator.php:17 PhanTypeMismatchProperty Assigning \Domain\PriceConverter to property but \Domain\PriceComparator::priceConverter is intsrc/Domain/PriceComparator.php:35 PhanNonClassMethodCall Call to method convert on non-class type int

 

Phan is amazing - it reads your entire code and performs multiple checks on it, including comparing phpdoc declarations with actual variables, methods, classes, etc. you can see https://github.com/phan/phan#features List of all features of.

Now, there are three fully automated tools in your project that can protect the quality of your code. All you need to do is run. / bin/phing manually, or attach it to your git hook or continuous integration. Your code will be checked for coding standards, duplicates, and formal errors. These checks should result in a more reliable runtime and less time spent reviewing code.

 

Recommended reading:

How to improve the quality of PHP code? Part II unit test

Posted by Alex-B on Sat, 07 Dec 2019 22:17:16 -0800