Detect unnecessary 'use' statements with PHP CodeSniffer

Aug 26, 2021 by Thibault Debatty | 5165 views

PHP Secure Software Development

https://cylab.be/blog/169/detect-unnecessary-use-statements-with-php-codesniffer

PHP Code Sniffer is a great tool to make sure your code is nicely written. Next to the default rules, you can also install and use additional rules (sniffs) to further enhance your code. Is here how to use PHPCS to detect (and remove) all unnecessary ‘use’ statements in your code.

php-code.jpg

Install PHPCS

If you don’t have PHPCS yet, you should first install:

composer require --dev squizlabs/php_codesniffer

Then create a configuration file called phpcs.xml:

<?xml version="1.0"?>
<ruleset name="PHP_CodeSniffer">
    <description>The coding standard for our project.</description>

    <!-- the standard that should be used -->
    <rule ref="PSR2"/>

    <!-- directories to check -->
    <file>app</file>
    <file>tests</file>
</ruleset>

This configuration will check that the code in directories app and tests is written according to the PSR2 standard.

You can now run PHPCS (and check that your configuration is correct) with:

./vendor/bin/phpcs

If you are using Laravel, you can find a typical configuration here: https://cylab.be/blog/22/using-php-codesniffer-in-a-laravel-project

Install Slevomat Coding Standard

Slevomat Coding Standard provides additional rules (sniffs), to help further improve your code. You can find the full list of sniffs at https://github.com/slevomat/coding-standard.

Installation is done with composer (as usual):

composer require --dev slevomat/coding-standard

Then you can add the sniffs to your phpcs.xml:

<?xml version="1.0"?>
<ruleset name="PHP_CodeSniffer">
    <description>The coding standard for our project.</description>
    <rule ref="PSR2"/>

    <!-- lines omitted for brevity -->
    
    <!-- Add rules from slevomat 
    https://cylab.be/blog/169/detect-unnecessary-use-statements-with-php-codesniffer -->
    <config name="installed_paths" value="../../slevomat/coding-standard"/>
    <rule ref="SlevomatCodingStandard.Namespaces.UnusedUses"/>
    
</ruleset>

You can now run PHPCS with all the sniffs as usual:

./vendor/bin/phpcs

Going further

Once you have detected (and removed) all unnecessary ‘use’ statements from your code, you can also remove all unused composer dependencies.

This blog post is licensed under CC BY-SA 4.0

This website uses cookies. More information about the use of cookies is available in the cookies policy.
Accept