最近在看 PHP 之道,看見 程式碼風格指南 章節的 php-cs-fixer。
php-cs-fixer 是能夠自動幫你修證程式碼風格,不只是格式化。
如果只需要程式碼儲存時自動格式化的,PhpStorm 可以開啟這個:
之前看別人發的項目,很多都是沒有格式化的,至少以上PhpStorm 儲存時自動格式化也沒有開啟吧。
接下來開始講下,開啟儲存自動 php-cs-fixer 修正程式碼的方法。
這邊使用全域安裝
composer global require friendsofphp/php-cs-fixer
參考https://cs.symfony.com/doc/installation.html
在項目根路徑下,新檔案:.php-cs-fixer.php,內容如下:
<?phpuse PhpCsFixer\Config;use PhpCsFixer\Finder;$rules = [ '@PHP80Migration' => true, 'ordered_imports' => [ 'sort_algorithm' => 'alpha', ], 'class_attributes_separation' => [ 'elements' => [ 'const' => 'one', 'method' => 'one', 'property' => 'one', ], ],];$finder = Finder::create() ->in([ __DIR__.'/app', __DIR__.'/config', __DIR__.'/database', __DIR__.'/resources', __DIR__.'/routes', __DIR__.'/tests', ]) ->name('*.php') ->notName('*.blade.php') ->ignoreDotFiles(true) ->ignoreVCS(true);return (new Config()) ->setFinder($finder) ->setRules($rules) ->setRiskyAllowed(true) ->setUsingCache(true);
然後在PhpStorm 設定
講下可能需要講的
當我們進行儲存時,它就會自動修正程式碼,在這裡是修正為PHP 7 以上的風格。
/Users/dogeow/.composer/vendor/bin/php-cs-fixer fix /Users/dogeow/PhpstormProjects/antic-api/routes/console.php -vvv --diff Cannot load Xdebug - it was already loaded PHP CS Fixer 3.3.2 Trinacria by Fabien Potencier and Dariusz Ruminski Runtime: PHP 8.0.8 Loaded config default from "/Users/dogeow/PhpstormProjects/antic-api/.php-cs-fixer.php". Using cache file ".php-cs-fixer.cache". Paths from configuration file have been overridden by paths provided as command arguments. F 1 / 1 (100%) Legend: ?-unknown, I-invalid file syntax (file ignored), S-skipped (cached or empty file), .-no changes, F-fixed, E-error 1) routes/console.php (assign_null_coalescing_to_coalesce_equal) ---------- begin diff ---------- --- /Users/dogeow/PhpstormProjects/antic-api/routes/console.php +++ /Users/dogeow/PhpstormProjects/antic-api/routes/console.php @@ -90,5 +90,5 @@ }); Artisan::command('test', function () { - $taskTag['name'] = $taskTag['name'] ?? 'url'; + $taskTag['name'] ??= 'url'; }); ----------- end diff ----------- Fixed all files in 0.024 seconds, 14.000 MB memory used 进程已结束,退出代码为 0
以上是php-cs-fixer大有用處!能自動修證程式碼風格~的詳細內容。更多資訊請關注PHP中文網其他相關文章!