LoginSignup
25
14

More than 3 years have passed since last update.

PHP で未使用の use import を削除する方法

Last updated at Posted at 2016-12-06

方法1: PhpStorm の整形機能を使う

IDE の PhpStorm を使う場合、メニューバーの Code メニューの中にある Show Reformat File Dialog ( ⌥⇧⌘L ) を表示して Optimize imports にチェックを付けて実行すると、未使用の use import を削除できます。

Reformat Code ダイアログ

一度チェックを入れて実行すると次以降は Reformat Code ( ⌥⌘L ) をするだけで削除できるようになります。

追記: コード整形をせずに use 一覧の最適化だけを行いたい場合は Optimize Imports ( ⌃⌥O ) で出来ます。

方法2: PHP-CS-Fixer を使用する

コード整形ツールの PHP-CS-Fixer で整形ルールを設定して実行することでも削除できます。

コマンドラインで実行できるため、PhpStorm 以外のエディタを使っている場合でも削除できます。

PHP-CS-Fixer とは

The PHP Coding Standards Fixer tool fixes most issues in your code when you want to follow the PHP coding standards as defined in the PSR-1 and PSR-2 documents and many more.

ref. https://github.com/FriendsOfPHP/PHP-CS-Fixer/

コーディング規約の PSR-1, PSR-2 に沿ってコードを整形してくれるコマンドラインツールです。

削除するコマンド例

# PHP-CS-Fixer 2.0 以降を使う場合
php-cs-fixer fix target.php --rules=@PSR2,no_unused_imports
# PHP-CS-Fixer 1.x を使う場合
php-cs-fixer fix target.php --level=psr2 --fixers=unused_use 

PSR-2 ( --level=psr2 ) のルールでは未使用 use の削除は行われないため、 --fixers オプションで削除するためのルールを追加しています。

バージョン2.0以降からそのルール名が変更されているため、注意が必要です。

  • 1.x: unused_use
  • 2.0以降: no_unused_imports

PHP ユーザーズグループはいいぞ

この記事の内容は Slack の PHP ユーザーズグループで質問して頂いた情報を元に解決して書かれたものです。多謝。

誰でも参加できるので是非どうぞ。

25
14
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
14