Skip to content

Automated preparation for Drupal 9

Shawn Duncan edited this page Apr 22, 2020 · 4 revisions

My primary motivation for adding PHPStan to this collection of pre-commit hooks for PHP is to watch for the use of deprecated code in preparation for Drupal 9 compatibility.

Setup

Here's how you can set this up for your own project:

  1. Install pre-commit. pre-commit is written in Python and requires Python 3.7. The linked installation instructions detail how you can use homebrew on macOS or pip in any operating system to install pre-commit.

    • pip install pre-commit
    • homebrew install pre-commit
  2. Add phpstan and the deprecation rules to your codebase via composer: composer require --dev mglaman/phpstan-drupal-deprecations

  3. Configure PHPStan by creating a file named phpstan.neon in the root of your project that loads the deprecation check:

    includes:
      - vendor/mglaman/phpstan-drupal-deprecations/deprecation_testing.neon
  4. Create a file named .pre-commit-config.yaml in the root of your project that contains the phpStan hook call:

    repos:
    - repo: https://github.com/digitalpulp/pre-commit-php.git
      rev: 1.4.0
      hooks:
      - id: php-stan
        files: \.(php|module|inc|install|profile|theme)$
  5. Run pre-commit install in your project to install the commit hooks into your repository. More information is available in pre-commit documentation to customize running these hooks on commit or push. By default, pre-commit will check the files included in every commit for Drupal deprecations.

  6. You can add other hooks as you like to .pre-commit-config.yaml and you can check all files in your project using pre-commit run --all-files

Example

In the bad.module file the following code is written:

function bad_idea() {
  $node = node_load(1);
}

So with the above in place you will see this on an attempted commit that includes bad.module:

$ git commit -m "deprecation test"

PHPStan..................................................................Failed
- hook id: php-stan
- exit code: 1

Begin PHPStan
Running command  vendor/bin/phpstan analyse docroot/modules/custom/bad/bad.module
────────────────────────────────────────────────────────────────────────────────
Note: Using configuration file /Users/shawnduncan/DockerSites/test/phpstan.neon.
────────────────────────────────────────────────────────────────────────────────
Errors detected by PHPStan...
────────────────────────────────────────────────────────────────────────────────
 ------ -------------------------------------------------------
  Line   modules/custom/bad/bad.module
 ------ -------------------------------------------------------
  18     Call to deprecated function node_load():
         in drupal:8.0.0 and is removed from drupal:9.0.0. Use
         \Drupal\node\Entity\Node::load().
 ------ -------------------------------------------------------

 [ERROR] Found 1 error
Clone this wiki locally