Top PHP Static Code Analysis Tools for Drupal
Introduction
There are so many ways to solve a coding task. Each developer has a personal vision and style. This also means there are many opinions about selected approaches and code quality. What one developer values in terms of code quality may be very different than what other developers value.
On the other hand, development teams are under pressure. Quality releases need to be delivered on time. Coding and compliance standards need to be met. And bugs are not an option. How can a developer survive in this world and not go crazy?
Table of contents
A code review can help you!
Code review is a part of the software development process that involves reviewing and testing the source code to identify bugs and potential improvements. An effective code review prevents bugs and errors, improving code quality at an early stage of the development process.
Here’s what you can accomplish with code reviews:
- Ensure that there are no obvious bugs in the code.
- Make every member of the team responsible for code quality.
- Confirm that new code follows guidelines and coding standards.
- Improve team members’ expertise. As a senior developer typically conducts a code review, a junior developer may use this feedback to improve their coding.
- Increase the efficiency of new code.
Manual code reviews can be partially automated, at least with automatic checks that make sure new code follows best practices and the latest standards. At Five Jars, we think that if anything can be automated, it should be automated. For this task, we have developed static code analyzers. We are going to talk about some of them below.
What is a static code analysis?
While everybody agrees that code reviews are extremely important, there is a high man-hour cost to them. So developers are always looking for a way to reduce the amount of time spent on code reviews while enhancing the results. And this is where static analysis tools come in – they can automate some of the review processes and make life easier for developers.
Static code analysis usually refers to the use of tools that attempt to detect possible vulnerabilities in "static" non-running source code.
There are tons of tools that allow static code reviews for any programming language. For PHP, you can use this perfect list of static analysis tools. Of course, you don’t need to use them all, but a few tools can really help your team.
Let’s review the most popular and helpful tools.
PHP_CodeSniffer and Coder
Most likely, you are familiar with PHP_CodeSniffer because it is one of the most popular and easy-to-use static analysis tools. PHP_CodeSniffer is a set of two PHP scripts: the main phpcs script that tokenizes PHP, JavaScript, and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations.
PHP_CodeSniffer Standards Composer Installer Plugin is a convenient way to add codesniffer rulesets to your projects via the composer. No more symbolic linking of directories, checking out repositories on specific locations, or changing the phpcs configuration.
This plugin executes the following steps:
- Searches for phpcodesniffer-standard packages in all of your currently installed Composer packages.
- Matching packages and the project itself are scanned for PHP_CodeSniffer rulesets.
- Call PHP_CodeSniffer and configure the installed_paths option.
PHP_CodeSniffer has many possible options and parameters, so using a phpcs Configuration File is the best practice. If you run PHP_CodeSniffer without specifying a coding standard, PHP_CodeSniffer will look in the current directory and all parent directories for a file called either .phpcs.xml, phpcs.xml, .phpcs.xml.dist, or phpcs.xml.dist. If one of the files is found, configuration information will be read from this file, including the files to check, the coding standard to use, and any command-line arguments to apply.
For example, the following config uses the AcquiaDrupalStrict ruleset. It ignores node_modules, vendors, and minified JS/CSS files, and runs analysis only for custom code located in modules/custom and themes/custom directories.
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="Project">
<description>PHP_Code Sniffer configuration for your amazing project.</description>
<arg name="colors"/>
<arg value="s" />
<arg name="cache" value=".phpcs-cache"/>
<arg name="parallel" value="10"/>
<rule ref="AcquiaDrupalStrict">
<exclude name="Drupal.InfoFiles.AutoAddedKeys.Version"/>
</rule>
<arg name="extensions" value="php,module,inc,install,test,profile,theme,css,info,txt,md,yml"/>
<exclude-pattern>/node_modules/</exclude-pattern>
<exclude-pattern>/dist/</exclude-pattern>
<exclude-pattern>*.min.*</exclude-pattern>
<exclude-pattern>vendor/*</exclude-pattern>
<file>./web/modules/custom</file>
<file>./web/themes/custom</file>
</ruleset>
How to use PHP_CodeSniffer in Drupal?
The Coder module provides a set of rules that tell PHP_CodeSniffer whether code meets Drupal coding standards or not. Specifically, there are two rulesets, Drupal and DrupalPractice.
Another way to set up PHP_CodeSniffer for Drupal is the Acquia Coding Standards for PHP. The ruleset is even more strict than Drupal and DrupalPractice. In fact, this is not just one ruleset, but a collection of PHP_CodeSniffer rules for PHP projects, including Drupal modules. Rules are split into rulesets according to the project language and framework:
- AcquiaPHP – general rules that can be used for any PHP project and don’t relate to any framework.
- AcquiaDrupalStrict – incorporates AcquiaPHP and adds all Drupal coding standards and best practices sniffs. It’s recommended for new Drupal projects and teams familiar with Drupal coding standards.
- AcquiaDrupalTransitional – a simplified version of Drupal and DrupalPractice rulesets. It’s perfect for teams new to Drupal coding standards.
Twigcs
Are you missing the checkstyle for Twig? Twigcs come in to check your templates for violations of coding standards. By default, Twigcs uses Twig 3. You can use an older Twig version using the twig-version option.
PHPStan
PHP_CodeSniffer is a perfect tool to check coding standards, but it has its own limitations. CodeSniffer analyzes each file separately, line by line, without any code execution context. For example, it can’t check if the class exists or if the wrong object is passed to a method.
PHPStan is a static analysis tool that allows you to bypass these restrictions. PHPStan uses another approach – it tries to take into account code context and dependencies.
By default, it checks:
- The existence of classes.
- The presence and availability of methods, the number, and arguments passed.
- The existence and visibility of class variables, as well as their type.
- The existence of local variables, etc.
If you want to learn more, you can check out the perfect introduction to the tool, written by PHPStan’s author.
PHPStan supports extensions, and this makes it a very flexible tool. There are many official and unofficial extensions for Doctrine, Symfony, Laravel, etc.
How to use PHPStan with Drupal?
PHPStan also has weaknesses. It requires transparent autoloading – PHPStan relies on being able to load classes or functions through the Composer's generated autoload information. The autoload file doesn’t contain any information about enabled Drupal modules or themes. That’s why PHPStan cannot analyze Drupal projects properly.
Phpstan-drupal is an extension for PHPStan created by mglaman to solve these problems. The extension uses a set of tricks to load all services and PHP files without connecting to the database. Here’s a detailed article about what’s under the hood.
Drupal-check is the CLI tool for running checks on a Drupal codebase. It’s based on PHPStan’s phpstan-drupal and is implemented by the same author. By default, the tool checks the code for deprecations, a very helpful feature when you are migrating from Drupal 8 to Drupal 9. But it also supports default code analysis for errors and mistakes.
GrumPHP
Another interesting tool that allows you to easily check your code before each commit is GrumPHP. GrumPHP helps you to set up pre-commit GIT hooks to check your code with different analysis tools, including those that we discussed above. It has a set of common tasks built-in.
For example:
- ESLint – a static analysis tool for JS code. ESLint covers both code quality and coding style issues.
- Git branch name – ensures that the current branch name matches the specified patterns. It can be helpful if you are working with JIRA and want all branches to contain the issue number.
- Phpcs – runs PHP_CodeSniffer for your code.
- PHPStan – runs PHPStan analysis for your code.
- Twigcs – runs TwigCs analysis for your twig templates.
GrumPHP can be configured in a grumphp.yml or grumphp.yml.dist file in the root of your project. In the config file, you can define necessary tasks and specify additional params.
# grumphp.yml
grumphp:
hooks_dir: ~
hooks_preset: local
git_hook_variables:
VAGRANT_HOST_DIR: .
VAGRANT_PROJECT_DIR: /var/www
EXEC_GRUMPHP_COMMAND: exec
ENV: {}
stop_on_failure: false
ignore_unstaged_changes: false
hide_circumvention_tip: false
process_timeout: 60
ascii:
failed: grumphp-grumpy.txt
succeeded: grumphp-happy.txt
parallel:
enabled: true
max_workers: 32
fixer:
enabled: true
fix_by_default: false
environment:
files: []
variables: {}
paths: []
tasks: {}
testsuites: []
extensions: []
See the official GrumPHP documentation for details.
Why are manual code reviews also important?
Manual reviews are still required to achieve good quality and security. It’s important to highlight that static analysis is not a panacea – automated static analysis and manual reviews complement each other. So why are manual reviews still required?
- Humans can find defects that even perfect analysis tools miss. Understanding the intention of what the code is meant to do provides human reviewers the ability to find non-obvious problems that cannot be detected without understanding the context.
- Review is more than just code: Reviews should be performed on all aspects of the software, including requirements, design, and code.
- Manual reviews help mentor new developers, ensure consistency in implementation, and strengthen team cohesion. Code reviews create the ability to share your perspective and discover new ways of doing the same things.
We hope that these tools help you make code reviews faster and more efficient. Write cool code, do perfect code reviews, and May the Force be with you!
P.S. If you have any comments or suggestions, feel free to use the contact form below to share them with us.
LET'S CONNECT
Get a stunning website, integrate with your tools,
measure, optimize and focus on success!