Taking too long? Close loading screen.
Connect with us


PHP code quality tools to check and improve your code



a good mentor is better than any quality tool

They were coded by Dave, your colleague developer.

The classes are full of formatting errors, poor indentation, and weird one letter variables. There are so many dependencies you need to scroll down for minutes to escape the bloated constructor.

Shacking, you open the unit tests to understand how it should work… but they don’t exist. Horror and misfortune!

You could ask Dave to come to your desk, yelling at him that you never saw anywhere such a crappy code, cursing him and his family for generations to come.

However, since you are such a respectful human being, you know it’s not a good solution. Teaching instead of blaming always gives better results.

With a calm worthy of a Zen monk, you first fix the bug driving your boss crazy with Dave’s help. Then, you decide to introduce to your team some code quality tools.

You’ve got a good approach dear reader: code quality tools are essential to write solid and error-free PHP code. It can help your colleagues detect defects in the codebase and teach them some key concepts.

Don’t forget however that the advice and the data they can provide won’t be appropriate everywhere. As often, it depends largely on the context: is your codebase large? Is there a good reason the cyclomatic complexity is high for some function?

If you are already bored by this article and just want to see a plain PHP tools list, you can directly go to the reference list at the end.

The last thing before diving in: tools presented in this article analyze or format your code. I won’t speak about testing.

[Read: 3 concrete steps to learning a programming language]

There are always multiple ways to install the tools described here.

My personal preference is to use the composer’s global package installation using cgr to avoid dependency problems on the global scope.

You can as well use the PHAR format, in most cases.

You can refer to the documentation of each tool to have every possible way of installing them.

In your terminal

All the tools can be used in the terminal. Most of the time you just need to pass the codebase’s path as an argument and voila! I describe this process for every tools in this article.

I advise you to call the tools from the main folder of your project. Every example assume that your codebase is in the folder src.

In Vim / Neovim

You can easily configure in Vim every tool you want and let them parse your open files.

With the plugin neomake you can plug easily PHPMD, PHPSTAN, and PHPCS to Vim. It will display in the gutter warnings and errors. Very handy!

You can even create your own makers to use every PHP code quality tools you want. As a reference, you can consult my neomake config file.

In PHPStorm

Since I don’t use PhpStorm anymore, I won’t explain how to install these tools in the IDE.

Nevertheless here some handly links to Jetbrain’s documentation:

I wouldn’t write any line of code without the following plugins. They will format your code properly and gives you precious advice.

PHP-CS-Fixer (PHP coding standards fixer)

Let’s begin by the cause of long meetings, hatred behavior, and murder impulses: code formatting rules. A great example of Parkinson’s Law of Triviality.

Personally I don’t have any preferences regarding code formatting. What I care about is to have a consistent one:

  • It’s easier to read
  • It frees your mind for more important questions

PHP-CS-fixer is a simple tools that allows you to format your code automatically. By default, PSR-1 and PSR-2 rules are used but you can define your own formatting rules.

With the following command you can format an entire codebase:

$ php-cs-fixer fix src/

You have as well the possibility to preview the modifications without applying them (--diff option) or you can precise the rules (--rules option) you want to use.

PHPCS (PHP CodeSniffer)

PHP CodeSniffer is a very good tool to output the coding standards violations you have in your codebase. Two command line scripts can be used: phpcs to output the actual coding standards flaws, and phpcbf which can fix some errors for you.

You can type for example:

$ phpcs src/

The output will look like that:

FILE: /home/superCoolUser/mySuperProject/src/Model/SuperModel.php
------------------------------------------------------------------------------------------ 2 | ERROR | [ ] Missing file doc comment 14 | ERROR | [ ] Missing @category tag in class comment 20 | ERROR | [ ] Missing doc comment for function __construct() 34 | WARNING | [ ] Line exceeds 85 characters; contains 93 characters 57 | ERROR | [x] Opening parenthesis of a multi-line function call must be the last content on the line 60 | ERROR | [ ] Expected "if (...) {n"; found "if(...) {n" 63 | ERROR | [x] Closing parenthesis of a multi-line function call must be on a line by itself

As you can see phpcbf can fix automatically two errors for you by typing:

$ phpcbf src/Model/SuperModel.php

You can use the default coding standard shipped with PHP Code Sniffer or you can easily implement your own.

PHPMD (PHP Mess Detector)

PHPMD will display the possible bugs and misuses of the language in your application.

Here how to do the magic:

$ phpmd src/ text cleancode

PHPMD will scan the directory and sub-directories of your project and output in plain text the errors found. You can as well create an html or xml output by replacing the text option in the command line above.

In this example, we use the cleancode ruleset but you can obviously change it or create your own.

Do you want to output the errors in a file? Easy:

$ phpmd src/ html cleancode --reportfile ~/phpmd.html

If you choose xml as output you will have more information regarding the rule set as following:

  name="/home/mySuperUser/mySuperProject/src/randomClass.php">  beginline="61" endline="61" rule="BooleanArgumentFlag" ruleset="Clean Code Rules" externalInfoUrl="http://phpmd.org/rules/cleancode.html#booleanargumentflag" priority="1"> The method notThatCoolMethod has a boolean flag argument $badBoolean, which is a certain sign of a Single Responsibility Principle violation.   beginline="102" endline="104" rule="ElseExpression" ruleset="Clean Code Rules" externalInfoUrl="http://phpmd.org/rules/cleancode.html#elseexpression" priority="1"> The method superMethod uses an else expression. Else is never necessary and you can simplify the code to work without else.  

You can see for example the priority of the rules violated. You can then refine your result by using the --minimumpriority option for example.

In short: PHPMD is a great tool I really encourage you to use. It will detect a lot of potential problems in your code and will save you hours of debugging.

Your boss will be so happy he will increase your salary by 200%. Guaranteed.

PHPStan (PHP Static Analysis Tool)

PHPStan is another tool to have in your toolbox. Does it aim? Output errors like a compiled language would display during compilation. It’s a good complement to PHPMD.

You can run it as follow:

$ phpstan analyse src/ --level=7

You can precise the strictness of PHPStan with the level option. The minimum is level 0, the maximum level 7.

To give you an idea here an example of the output:

 ------ ----------------------------------------------------------------------- Line src/MySuperModels/RandomModel ------ ----------------------------------------------------------------------- 78 Instantiated class AppServiceApiInvalidArgumentException not found. 82 Instantiated class AppServiceApiInvalidArgumentException not found. 93 Method AppServiceApiClientClientInterface::post() invoked with 3 parameters, 4 required. 103 Casting to string something that's already string. ------ -----------------------------------------------------------------------

Like the other tools, you can create your own rules.

PHPUnit and the CRAP metric

This article is not about the unit test. I assume you know that unit testing your code is far more important than anything present in this article.

PHPUnit can as well display very interesting information: the CRAP metric.

CRAP uses the cyclomatic complexity with the code coverage of your code to display what might be the code difficult to change in your application.

The more the CRAP index is high, the more your code will be considered as “crappy.”

Indeed if your code has a great complexity but a low code coverage, you can expect it to cause unfortunate bugs each time you change it. You won’t even notice till your boss yells at you. Expect Dave, your colleague developer, trying to push you even more down for him to shine in the shadow of your shame.

To display the CRAP metrics, you need to produce a code coverage report:

$ phpunit phpunit --coverage-html ./tempFolder

This will create HTML files in the tempFolder directory. You can open the index.html in there and click on the dashboard link to finally contemplate the CRAP indicator.

crap metricJourney to the center of the CRAP

Please remember, however: code coverage doesn’t mean that your code is well tested. This is an entirely different topic I will keep for another article.

Checking your PHP code deeper

I use the following tools to make sure that the project I work on goes in the right direction. They can help you with seeing the big picture.

They can as well be a real-life savior when you need to work on an unknown (legacy) application. They can be a great help for refactoring.


PhpLoc is a very good tool to get an idea of the size of a project.

You can execute on your codebase:

$ phploc src

This will output something like that:

Size Lines of Code (LOC) 61 Comment Lines of Code (CLOC) 0 (0.00%) Non-Comment Lines of Code (NCLOC) 61 (100.00%) Logical Lines of Code (LLOC) 23 (37.70%) Classes 17 (73.91%) Average Class Length 17 Minimum Class Length 17 Maximum Class Length 17 Average Method Length 3 Minimum Method Length 1 Maximum Method Length 7 Functions 0 (0.00%) Average Function Length 0 Not in classes or functions 6 (26.09%) Cyclomatic Complexity Average Complexity per LLOC 0.26 Average Complexity per Class 7.00 Minimum Class Complexity 7.00 Maximum Class Complexity 7.00 Average Complexity per Method 2.20 Minimum Method Complexity 1.00 Maximum Method Complexity 4.00 Dependencies Global Accesses 0 Global Constants 0 (0.00%) Global Variables 0 (0.00%) Super-Global Variables 0 (0.00%) Attribute Accesses 7 Non-Static 7 (100.00%) Static 0 (0.00%) Method Calls 14 Non-Static 14 (100.00%) Static 0 (0.00%) Structure Namespaces 1 Interfaces 0 Traits 0 Classes 1 Abstract Classes 0 (0.00%) Concrete Classes 1 (100.00%) Methods 5 Scope Non-Static Methods 5 (100.00%) Static Methods 0 (0.00%) Visibility Public Methods 3 (60.00%) Non-Public Methods 2 (40.00%) Functions 0 Named Functions 0 (0.00%) Anonymous Functions 0 (0.00%) Constants 1 Global Constants 0 (0.00%) Class Constants 1 (100.00%) 

Those data can give you already some clues about the project:

  • Comment lines of code is never good. Get rid of it without a second thought.
  • Too high Average Class length is usually not good either. Split the god classes.
  • Too high Average Method length is again not good. For the sack of your colleagues, split them.
  • Cyclomatic complexity can indicate a bit of everything and anything. Trusting something like CRAP might be wiser.
  • Avoid unnecessary Dependencies. Don’t forget that globals accesses, constants and variables can bring you many problems.
  • Avoid abstract classes as much as possible: remember composition over inheritance.

In a nutshell: a very simple and valuable tool.

PHP insight

PHP Insight is a pretty good static analyzer that will give you much advice to improve the quality of your code.

You can use it as follow:

phpinsights analyse ./src

First, It will give you a quick overview of your codebase:

PHP Insight first screen

Then, it will provide you much advice:

PHP Insight second screen

This is a really useful tool. You can as well format the output (JSON for example) or even create your own rules!

PHPCPD (PHP Copy past detector)

PHPCPD will scan your codebase and output the code duplicated.

You can use it by typing:

$ phpcpd src/

PHPCPD will produce this kind of output:

phpcpd 4.0.0 by Sebastian Bergmann. Found 1 clones with 44 duplicated lines in 2 files: - /home/superUser/src/superFile.php:11-55 /home/superUser/src/superFolder/superFile.php:11-55 5.04% duplicated lines out of 873 total lines of code. Time: 29 ms, Memory: 4.00MB

You can include multiple files instead of a whole directory, exclude some files (or paths) or even output the result in a XML file.

Keep in mind though: if you go to the DRY principle violation hunting in your codebase, keep in mind that code duplication doesn’t necessarily imply DRY violation.

PHPMND (PHP magic number detector)

This tool is pretty specific: it can help you to find magic numbers in your code.

The easiest way to use it:

$ phpmnd src/

Here the output:

-------------------------------------------------------------------------------- httpClient/myHttpClient.php:98. Magic number: 200 > 98| if ($response->getStatusCode() != 200) { -------------------------------------------------------------------------------- service/superClass.php:47. Magic number: 8 > 47| for ($i = 0; $i < 8; $i++) { -------------------------------------------------------------------------------- 

You can play with a lot of options, like the possibility to ignore numbers, exclude files / paths / extensions…


Did you ever work on a project full of unnecessary dependencies, wondering how to understand this nightmare? Do you want to verify if your wonderful project is not mutating into a complex Big Ball of Mud?

dePHPend can help you grandly on that matter.

You can use it as follow:

$ dephpend metrics src/

This output will then appear magically:

example dephpend output

As you can see, dePHPend will output the number of Afferent Coupling, the number of Efferent Coupling and display an instability indicator based on them.

In clear:

  • No class depend on the class AppKernel
  • The class AppKernel depends on five other classes

The instability score is high here: this class couple other classes together but is never used!

You can as well output plain text or UML for example.


churn-php will display the classes you should refactor based on the cyclomatic complexity and the number of commit the class has.

This is a pretty interesting approach. A very complex class that is often modified has indeed a high chance to introduce bugs.

As the other tools, it is very straightforward to use:

$ churn run src/

Here the result:

| File | Times Changed | Complexity | Score |
| src/Service/classToRefactor.php | 12 | 8 | 0.441 |
| src/Service/anotherClass.php | 3 | 15 | 0.185 |

The higher the score, the greater the need to refactor.


Deprecated functions are bad. They can create very weird bugs difficult to debug. This tool can help you detect them in your shiny application. You can precise the version of PHP you work with and your main codebase directory as follow:

$ phpcf --target 7.1 src

And here the usual possible output:

phpcf output


Last but not least: if you are a metric lover, PhpMetrics will be your daily fix. It will output a lot of metrics about your project.

You need to type something like that:

$ phpmetrics --report-html=myreport.html src/

The HTML output will be full of diagrams and numbers.

Now keep in mind that metrics are not necessarily the absolute truth, it really depends on your project. I won’t explain everything this tool can output here, maybe in a future article?

My experience showed me that software entropy is a real thing. The more you will modify your application, the more the application has chances to break. Your application will inevitably become more complex.

These PHP code quality tools can definitely help you in that matter. Since your codebase will be more and more buggy, refactoring is a necessity and these tools can show you where to start. On a daily basis, they can give you good advice on all these little things you need to take care of to keep your codebase healthy.

Keep in mind though: they are a good complement but not a replacement for a solid test suite, beginning by good unit tests.

Do you use other tools than the ones described here? Do you use them differently? Don’t hesitate to help the community by sharing your experience.

This article was written by Matthieu Cneude and was originally published on The Valuable Dev, a blog focusing on the important and timeless concepts in software development. You can read the piece here

Read next: Digital note-taking takes a step forward with the SyncPen


Continue Reading
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *


The Apple Watch Series 6 Is Already $20 Off



Best Tech DealsBest Tech DealsThe best tech deals from around the web, updated daily.

Apple Watch Series 6 (44mm) | $415 | Amazon
Apple Watch Series 6 (40mm) | $385 | Amazon


It’s only been out a week since launch and we’re already seeing discounts on the Apple Watch Series 6. Amazon has some 40mm models down to $375, while the 44mm falls to $415, both about $20 off and shipping anywhere between 1-4 weeks out.


The Apple Watch Series 6 runs laps around the competition as far as technology is confirmed. It features everything you love about the Series 5 watch like an ECG heart rate sensor, and also adds new tricks like a blood oxygen sensor and an always-on altimeter, making it more ideal than ever for fitness buffs.


Continue Reading


Samsung thinks its new 85-inch Interactive Display is the digital whiteboard for the COVID-19 classroom



Samsung would like you to believe its new 85-inch Interactive Display can bridge the gap between students in the classroom and students studying at home, now that blended-learning is the new normal across the country. In reality, it’s just a slightly bigger digital whiteboard — but assuming it doesn’t cost too much, the tweaked vision does sound intriguing.

Now that COVID-19 has swept the country, some students are huddling around tiny Chromebook screens at home while others stay in class, and Samsung’s internet-connected digital whiteboard promises to let students and teachers collaborate with each other, whether they’re in that classroom drawing on the board or adding to it in real-time from their laptop at home. The goal here isn’t to necessarily connect everyone better – they’ve had a few months to get a handle on that over Zoom – but rather to let the kind of collaboration that can happen when everyone’s together, happen while students are apart.

Samsung’s 65-inch Flip 2

While the Interactive Display is mostly just a larger version of Samsung’s existing Flip 2 digital whiteboards, the 85-inch size means it’s as large as an actual school whiteboard (though it weighs far more at 164 pounds). Compared to the previous 55- and 65-inch models, more students could theoretically use the board at once. Samsung imagines the display primarily mounted in a classroom where they can use its 4K touchscreen and support for four pens (it comes with two) to write and draw; it supports up to 20 fingers (and pen tips) simultaneously. Teachers might be able to hook up multiple computers or other video sources to the display, too, with two HDMI 2.0 ports compared to the one on the Flip 2.

But before you petition your school for one, it’s worth mentioning that the device has no announced price. The 65-inch Flip 2 comes in at $2,599.00, and Samsung’s 85-inch TVs start at $1,799.99, so perhaps the Interactive Display won’t cost too much more than those? Still, most schools are even more constrained during the pandemic than they would be normally, and this screen doesn’t even come bundled with some of the education software Samsung is advertising. I think it would be great for these to be used in schools, but to me, Samsung’s framing for the Interactive Display sounds a little more opportunistic than realistic.


Continue Reading


How to enable dark mode on all of your essential apps



Welcome to TNW Basics, a collection of tips, guides, and advice on how to easily get the most out of your gadgets, apps, and other stuff.

Ah, dark mode — the charcoal gray color palette associated with night time and eyeball-saving. It’s not without its detractors, not even among my own colleagues. But there are plenty of people, including me, who can’t get enough of the dusty-colored theme. Luckily dark mode is available on just about every device and app — so we’ll walk you through how to make your digital life just a little bit darker.

Note that we’re going to show you how to enable dark mode on several of the most essential apps and services — there isn’t enough time or space on our servers to show you how to enable dark mode everywhere, as it’s a very omnipresent theme. But these will make a good starting point.

Social media

Most social media apps have added dark mode to make late-night browsing easier. Facebook, of all sites, is one of the latecomers. It only added dark mode with the latest redesign, which you can read about here. The dark mode toggle is in the main drop-down menu of the site. While Instagram doesn’t have an in-app dark mode option, it syncs to your phone’s dark mode — you can read about how that works here.

Twitter has a similar setting to Instagram, in that you can sync its color palette with the system settings — meaning, if your phone is already in dark mode, it’ll go dark automatically. You can also manually set it to dark mode by going to the settings, and looking for the dark mode toggle under “Display and Sound. You can read more about the options here.

Messenger originally only had dark mode via an emoji-based Easter egg, but it has since joined the bandwagon for real. In order to switch on dark mode, you just have to tap your profile picture and the toggle is right there at the top of the options. You can read more about it here.

Workplace apps

It’s not just social media that wants to spare your eyes. Several of your favorite workplace apps have also added dark mode settings, so even your work computer can look as sooty as a fireplace. For starters, Slack now has a dark mode available on its iOS and Android apps (which you can read about here) as well as its desktop client (which you can read about here).

Dark mode selection on Slack for desktop

WhatsApp has also added dark mode to its web and mobile version, albeit at different times. You can read about how to enable dark mode on the web client here, and on Android here. As with other apps mentioned here, WhatsApp will automatically go into dark mode on iOS when iOS itself is set to dark mode.

Google has also added dark mode to its Docs, Sheets, and Slides on Android, which you can read abut here. Also, it’s not a workplace app per se, but Google Play also has dark mode — in order to switch it on, you just need to go to the app settings and look for the Theme menu. You can read about it here.

Operating systems

Just like all of the above, the different operating systems for phones offer dark modes for you to turn on at night to make browsing or working easier on your eyes. Apple added dark mode to iOS 13, and as mentioned, turning it on will kick most apps into dark mode if it’s available. You can read about how to turn it on here. Similarly, Android introduced a Dark theme in the Android 10 update, which you can find in the Display settings.

Enable dark mode on iOS 13 from settings

If you want some variety, Windows 10 also has a light mode in addition to dark — you can find both in the personalization settings. You can read more about it here.

And that’s it! While this won’t necessarily make your whole life an obsidian paradise, it’ll at least put dark mode on all of your favorite apps. Good luck!


Continue Reading