Prevent composer soft dependencies

18 Apr 2024

Hello, everyone! Today, I would like to talk about a tool for tracking transitive dependencies called ComposerRequireChecker.

The Problem of Transitive Dependencies

The concept of transitive dependencies is detailed in the README of the package.

Direct dependencies of a project are specified in the composer.json file. These packages can also have their own dependencies - transitive, which are installed automatically.

Direct dependencies are used directly in the project's code. Transitive dependencies should only be used in direct dependencies. If a transitive dependency is used directly in the project's code, it must be added to composer.json as a direct dependency.

A real problem can arise when updating packages with composer update. The list of package dependencies may change, and a transitive dependency may be removed from the project. If a transitive dependency is used directly in the code, such code will stop working.

The Solution

ComposerRequireChecker solves this problem. It scans the project's code and composer.json file, and finds the use of transitive dependencies in the code.

Setting Up ComposerRequireChecker

The package is configured using a configuration file composer-require-checker.json. Example:

{
  "symbol-whitelist": [],
  "scan-files" : [
    "public/index.php",
    "bin/*.php",
    "src/*.php"
  ]
}

Configuration details are described in the README.

To run the check, download ComposerRequireChecker and execute the command:

php composer-require-checker.phar check --config-file=composer-require-checker.json composer.json

Running in CI/CD, Github Actions

To continuously monitor transitive dependencies, let's add the check to CI/CD. Here's an example for GitHub Actions:

- name: Run composer require checker
  run: |
      wget https://github.com/maglnet/ComposerRequireChecker/releases/download/4.10.0/composer-require-checker.phar
      php composer-require-checker.phar check --config-file=$(pwd)/composer-require-checker.json composer.json

Usage Example

An example of the ComposerRequireChecker's work can be seen in the placeholder-service.

While setting up the package, I discovered several transitive dependencies being used in the project's code. I added them to composer.json. Thus, ComposerRequireChecker helps to keep dependencies in order.

That's all for now. Thank you for your attention!