从PHP代码库中检测/删除未使用的`use`语句的最简单方法

时间:2012-03-27 18:35:58

标签: php

我已经搜遍过这样的事情,但我相信“使用”这个词对于任何有用的结果来说可能太常见了:

从PHP代码库中的类文件中删除所有未使用的use语句的最简单方法是什么?

编辑:为简单起见,我们可以忽略检测用于注释的use语句。

3 个答案:

答案 0 :(得分:21)

检查FriendsOfPHP的PHP-CS-Fixer https://github.com/FriendsOfPHP/PHP-CS-Fixer

答案 1 :(得分:7)

修改

我完全重写了它,所以现在它更强大了:

  • Traits和anonymous / lambda函数被忽略
  • 现在负责catch块,类扩展和接口
  • 缩进和评论无关紧要
  • 命名空间别名的多个声明也可以使用
  • 静态和对象类调用被识别为“用法”($ u-> getUsages())
  • 不对待完整和半合格的用法

测试文件 class.php:

<?php

use My\Full\Classname as Another, My\Full\NSname, Some\Other\Space;

/* some insane commentary */ use My\Full\NSname1; use ArrayObject;

$obj = new namespaced\Another;
$obj = new Another;

$a = new ArrayObject(array(1));

Space::call();

$a = function($a, $b, $c = 'test') use ($obj) {
  /* use */
};

class MyHelloWorld extends Base {
  use traits, hello, world;
}

这里是剧本:

<?php
class UseStatementSanitzier
{
  protected $content;

  public function __construct($file)
  {
    $this->content = token_get_all(file_get_contents($file));

    // we don't need and want them while parsing
    $this->removeTokens(T_COMMENT);
    $this->removeTokens(T_WHITESPACE);
  }

  public function getUnused()
  {
    $uses   = $this->getUseStatements();
    $usages = $this->getUsages();
    $unused = array();

    foreach($uses as $use) {
      if (!in_array($use, $usages)) {
        $unused[] =  $use;
      }
    }
    return $unused;
  }

  public function getUsages()
  {
    $usages = array();

    foreach($this->content as $key => $token) {

      if (!is_string($token)) {
        $t = $this->content;

        // for static calls
        if ($token[0] == T_DOUBLE_COLON) {
          // only if it is NOT full or half qualified namespace
          if ($t[$key-2][0] != T_NAMESPACE) {
            $usages[] = $t[$key-1][1];
          }
        }

        // for object instanciations
        if ($token[0] == T_NEW) {
          if ($t[$key+2][0] != T_NAMESPACE) {
            $usages[] = $t[$key+1][1];
          }
        }

        // for class extensions
        if ($token[0] == T_EXTENDS || $token[0] == T_IMPLEMENTS) {
          if ($t[$key+2][0] != T_NAMESPACE) {
            $usages[] = $t[$key+1][1];
          }
        }

        // for catch blocks
        if ($token[0] == T_CATCH) {
          if ($t[$key+3][0] != T_NAMESPACE) {
            $usages[] = $t[$key+2][1];
          }
        }
      }
    }
    return array_values(array_unique($usages));
  }

  public function getUseStatements()
  {
    $tokenUses = array();
    $level = 0;

    foreach($this->content as $key => $token) {

      // for traits, only first level uses should be captured
      if (is_string($token)) {
        if ($token == '{') {
          $level++;
        }
        if ($token == '}') {
          $level--;
        }
      }

      // capture all use statements besides trait-uses in class
      if (!is_string($token) && $token[0] == T_USE && $level == 0) {
        $tokenUses[] = $key;
      }
    }

    $useStatements = array();

    // get rid of uses in lambda functions
    foreach($tokenUses as $key => $tokenKey) {
      $i                   = $tokenKey;
      $char                = '';
      $useStatements[$key] = '';

      while($char != ';') {
        ++$i;
        $char = is_string($this->content[$i]) ? $this->content[$i] : $this->content[$i][1];

        if (!is_string($this->content[$i]) && $this->content[$i][0] == T_AS) {
          $useStatements[$key] .= ' AS ';
        } else {
          $useStatements[$key] .= $char;
        }

        if ($char == '(') {
          unset($useStatements[$key]);
          break;
        }
      }
    }

    $allUses = array();

    // get all use statements
    foreach($useStatements as $fullStmt) {
      $fullStmt = rtrim($fullStmt, ';');
      $fullStmt = preg_replace('/^.+ AS /', '', $fullStmt);
      $fullStmt = explode(',', $fullStmt);

      foreach($fullStmt as $singleStmt) {
        // $singleStmt only for full qualified use
        $fqUses[] = $singleStmt;

        $singleStmt = explode('\\', $singleStmt);
        $allUses[] = array_pop($singleStmt);
      }
    }
    return $allUses;
  }

  public function removeTokens($tokenId)
  {
    foreach($this->content as $key => $token) {
      if (isset($token[0]) && $token[0] == $tokenId) {
        unset($this->content[$key]);
      }
    }
    // reindex
    $this->content = array_values($this->content);
  }

}

$unused = new UseStatementSanitzier('class.php');

print_r($unused->getUnused());

/*
Returns:
Array
(
  [0] => NSname
  [1] => NSname1
)
*/

答案 2 :(得分:1)

这可能取决于代码的设置方式。如果您的代码使用如下命名空间:

namespace Foo
{
   <one or more classes in namespace Foo>
}

如果您只是单独检查每个文件,那么您可能会很好。这仍然意味着您必须解析PHP代码以查找use语句,然后确定使用哪些语句。

简单的方法是使用已经构建的工具。我最近开始使用PhpStorm IDE(30天免费路径,或early access program),当您在文件中有未使用的use语句时,它可以通知您(您甚至可以指定是否应该出现警告或错误)。它仍然需要你打开每个文件。但是你也可以检查你正在编辑的文件,最后你的代码会变得更干净。