A proactive approach for cleaner Drupal coding
So you are stuck in the cruft, struggling to create some semblance of sanity within a sea of code-rot. Code standards sound like a great idea for your project, but perhaps automated enforcement tools look like more of a pain than they’re worth. This post is intended for Drupal developers using PhpStorm who need fast, flexible, standards enforcement tools.
Maintaining a stringent standard for your codebase is a battle. On one hand, your code is cleaner, more unified, and easier to maintain. On the other hand, these little formatting rules cause frustration and time loss – especially if a tiny slip causes you to waste a full pipeline cycle just to pass an automated standards check. As they say, the best defence is a strong offence, and the tools proposed here will help you find and fix standards violations before they reach a pipeline.
Drupal recommends a tool called PHP Code Sniffer, aka phpcs, to scan your files for Drupal Code Standards violations. Thankfully, it also comes with a companion tool called PHP Code Beautifier and Fixer, aka phpcbf, which fixes the small, tedious violations for you.
The goal of this post is to get phpcs and phpcbf under your fingertips and into your habits. Only once you have hotkeys set-up to run these tools while coding will they become useful — instead of just annoying.
The steps are as follows:
- Install and set-up phpcs
- Create a custom combination of rulesets
- Integrate with PhpStorm for hotkeys and syntax highlighting
It may seem straightforward to install phpcs globally via Composer or apt, or to simply require it in your current composer project. However, a global install is not easy to customize and share. Instead, I recommend using a standalone repo that is specifically for your code standards tools. When your standards stand alone, they are easier to edit, share with teammates, and transfer to new work environments.
Here’s a simple repo to get you started:
- If you currently have phpcs or phpcbf installed globally, uninstall them before proceeding.
- Quick install with example repo:
git clone firstname.lastname@example.org:nilswloewen/drupal_code_standards.git
Once composer has installed phpcs for you, add it to your global path with:
NOTE: Adjust accordingly for your shell and OS of choice.
Next, you must tell phpcs which rulesets you have installed use.
The optional tool phpcodesniffer-composer-installer will automatically detect rulesets in your composer package and set your phpcs & phpcbf installed_paths for you. This is part of the example repo and the next step should have been done for you during “composer install”.
However, to set installed paths to rulesets manually run:
phpcs --config-set installed_paths vendor/drupal/coder/coder_sniffer,vendor/phpcompatibility/php-compatibility/PHPCompatibility
Then confirm that phpcs knows about the rulesets within the installed paths with:
You should see this list that confirms your rulesets:
The installed coding standards are ... PHPCompatibility, Drupal and DrupalPractice
You may need to set installed paths for phpcbf as well using the same process.
Out of the box, phpcs can only run one standard at a time. This is a problem when working with Drupal because we have 2 standards to follow. For this post I have added a third standard, PHPCompatibility, which is helpful when upgrading php versions on legacy projects.
- To combine standards we first create a custom ruleset that references multiple rulesets. Note that this is already included in the example repo as phpcs-custom-standards.xml.
- Then set this standard as your default. Use an absolute path to ensure your standard will be found no matter what context phpcs is called from.
phpcs --config-set default_standard ~/PATH/TO/drupal_code_standards/phpcs-custom-standard.xml
See the example standard for a few other helpful settings.
There are two levels of integration with PhpStorm: Passive and Active.
Passive code analysis with PhpStorm Inspections will give you syntax highlighting and hover-over explanations of the file you are currently working on.
This is quite helpful when dealing with one file at a time, but when you need to get an entire directory to pass standards, you need a way to hunt for violations.
Active analysis when you use phpcs to scan many files at once. You can do this through the terminal with a command like:
phpcs ~/module # Scans all applicable files in dir.
phpcs ~/module/example.php # Scans only a specific file.
However, it’s a pain to open a terminal window, navigate to the file you are working on, and then type a command. You’ll probably forget or neglect to check your work because of these extra steps involved. A better way to run phpcs is to set-up hotkeys within PhpStorm to scan your files instantly.
Configure PhpStorm inspections
Register phpcs and phpcbf as PHP Quality Tools.
Settings | Languages and Frameworks | PHP | Quality Tools | Code Sniffer
Enable the inspection.
Settings | Editor | Inspection | PHP | Quality Tools
- Set the extension list to match what Drupal standard sets: source
- DO NOT set the “Installed standard paths”, as this overrides what you have previously set in the command line.
- The refresh list button on “Coding Standard” should mimic what “phpcs -i” shows. Choose “Custom” Coding Standard and then click the ellipses to choose the path to your custom standards file (i.e. phpcs-custom-standards.xml).
- Click OK and your inspections should be working!
- Register phpcs and phpcbf as external tools.
Settings | Tools | External Tools
The “$FilePath” argument runs the tool against the file you are currently working on, or against a selected folder when in project view.
- Double check that this step works by running the tool from the main menu.
Tools | External Tools | phpcs
- This is the special sauce. Configure a keyboard shortcut for your new tools.
Settings | Keymap | External Tools
Right click on the external tool you just registered and add a keyboard shortcut. “Ctrl+Alt+Shift+Comma” was simply a combination that was not used anywhere else in my setup.
Bringing it all together
Now you can actively use phpcs and phpcbf while you code! I frequently use the phpcbf hotkey while writing new code to do the tedious stuff for me, such as creating doc blocks and pushing whitespace around. Here’s an example:
With phpcs and phpcbf now under your fingertips you are set to be much more assertive in your application of code standards!
Taking it to the next level
If you are using Gitlab for CI/CD, which I hope you are, another great strategy for enforcing standards is to create a pre-deployment job that scans your custom code for violations. This will keep your team (and you) in check by stopping standards violations from being auto-deployed.
After a few super annoying pipeline failures for minor syntax errors, you will want this next level of enforcement — git pre-commit hooks. I highly recommend using grumphp to manage this for you.
Best of luck keeping your code readable and up to snuff!
End-to-end Drupal services
As a full service Drupal agency, Acro Media has significant expertise in digital commerce architecture, ecommerce design, customer experience, software development and hosting architecture. If you’re looking for a Drupal agency dedicated to code and project quality, check us out. We would love the opportunity to talk.