Detect unused composer dependencies

May 13, 2020 by Thibault Debatty | 5339 views

PHP Secure Software Development

https://cylab.be/blog/53/detect-unused-composer-dependencies

If you are using composer to manage the dependencies of your PHP project (and you certainly should), it is very easy to end up using a lot of dependencies. And if your project lives long enough, some (or lots of them) will not be used anymore.

Keeping these unused dependencies has drawbacks:

  1. They may contain vulnerabilities that could lead to a complete hack of your application. A famous example is the CVE-2017-9841 vulnerability affecting Phpunit. This flaw allowed an attacker to execute code on any web application that used the affected versions of Phpunit.
  2. They may cause incompatibilities with other libraries. For example, you may not be able to install an interesting library because of an incompatibility with an old unused library.
  3. Or, in some other cases, you may not be able to update other libraries because the latest versions are not compatible with an old unused library. These updates are important. In some case they fix vulnerabilities that have been discovered.

Luckily, there is an easy solution to detect these unused dependencies: Insolita unused-scanner

Installation

composer require --dev insolita/unused-scanner

Usage

You will first have to create a configuration file. You can name it unused-scanner.php for example. Here is a typical example:

<?php

$projectPath = __DIR__;

// Declare directories which contains php code
$scanDirectories = [
    $projectPath . '/app/',
];

// Optionally declare standalone files
$scanFiles = [
];

return [
    'composerJsonPath' => $projectPath . '/composer.json',
    'vendorPath' => $projectPath . '/vendor/',
    'scanDirectories' => $scanDirectories,
    'scanFiles' => $scanFiles,

    // whitelisted packages
    'skipPackages' => ['laravel/tinker', 'guzzlehttp/guzzle'],
];

The, you can run the scanner:

vendor/bin/unused_scanner unused-scanner.php

Fixing

If unused dependencies have been detected, you can either:

  • remove them with composer remove cylab/system
  • move them to the require-dev section of your composer.json file, if these dependencies are only used for development

gitlab-ci

Finally, don't forget to add this test to your gitlab-ci.yml:

test:
  image: cylab/php72
  before_script:
    - COMPOSER_CACHE_DIR=composer-cache composer install
  script:
    - vendor/bin/unused_scanner unused-scanner.php

This blog post is licensed under CC BY-SA 4.0