moodlehq / moodle-cs

Moodle Coding Style

Home Page:https://github.com/moodlehq/moodle-cs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add a sniff for unused class imports

andrewnicols opened this issue · comments

<?php

use foo;
use bar;
use baz;

$example = new foo(baz::class);

The bar class import is unused and should be:

  • reported
  • removed

Drupal have a sniff for this:
https://packagist.org/packages/drupal/coder

https://git.drupalcode.org/project/coder/-/blob/8.3.x/coder_sniffer/Drupal/Sniffs/Classes/UnusedUseStatementSniff.php

It's been proposed for import into SquizLabs here:
squizlabs/PHP_CodeSniffer#1106

It's also part of the SlevoMat sniffs:
https://github.com/slevomat/coding-standard/blob/master/doc/namespaces.md#slevomatcodingstandardnamespacesunuseduses-

Yeah, I've been thinking about this for some good time, and I'd say that there are a few cases related also worth being considered:

  1. "use" uses straight under a namespace:
namespace mod_forum

use mod_forum\foo;
  1. Complete class-path uses of things declared as "use"
use mod_forum\foo;

$example = new \mod_forum\foo();
  1. I think that there are a few more around that I've seen and should have annotated in some of my namespaces notes.

In fact I've here a very basic shell script (from where we did the Epic adding namespaces to all test files), that was able to detect some of the cases. Maybe we should consider this within the "namespaces" epic, now that we have the apix.json in core and other things and start enforcing that area globally.

I'd say that "namespaces" and "phpdoc" should be our 2 very next areas in moodle-cs.

Ciao :-)