2022/03/21

[PHP] 如何在 VS Code 使用 php-cs-fixer 自動修正 coding style 格式

因應 PSR-12: Extended Coding Style,讓 VS Code 來幫忙自動修正程式碼風格

環境

  • PHP 8.0.15
  • Composer 2.2.6
  • friendsofphp/php-cs-fixer v3.6.0

php-cs-fixer

Composer 全域安裝

composer global require friendsofphp/php-cs-fixer

其他安裝方式: PHP-CS-Fixer 安裝文件

VSCode 套件

以前使用 junstyle.php-cs-fixer 的套件, 但是設定項目蠻多的, 相對繁索

現在換 mansoorkhan96.php-cs-fixer 套件, 幾乎可以是零設定

指定程式碼樣式規則, 變更成 @PSR12 即可

"php-cs-fixer.rules": "@PSR12",

建立規則檔 .php-cs-fixer.php 在 VS Code 設定指定 php-cs-fixer.config 的檔案路徑

例如:

// mac, linux
"php-cs-fixer.config": "/full/config/file/path"

// windows
"php-cs-fixer.config": "C:\\Users\\username\\.vscode\\.php-cs-fixer.php"

.php-cs-fixer.php 範例

<?php
// PHP-CS-Fixer: https://github.com/FriendsOfPHP/PHP-CS-Fixer
// Example config
$config = new PhpCsFixer\Config();
return $config
->setRules([
'@PSR12' => true,
'new_with_braces' => false,
'array_indentation' => true,
'array_syntax' => ['syntax' => 'short'],
'combine_consecutive_unsets' => true,
'multiline_whitespace_before_semicolons' => true,
'single_quote' => true,
'blank_line_before_statement' => true,
'braces' => [
'allow_single_line_closure' => true,
],
'concat_space' => ['spacing' => 'one'],
'declare_equal_normalize' => true,
'function_typehint_space' => true,
'include' => true,
'lowercase_cast' => true,
'no_multiline_whitespace_around_double_arrow' => true,
'no_spaces_around_offset' => true,
'no_unused_imports' => true,
'no_whitespace_before_comma_in_array' => true,
'no_whitespace_in_blank_line' => true,
'object_operator_without_whitespace' => true,
'single_blank_line_before_namespace' => true,
'ternary_operator_spaces' => true,
'trailing_comma_in_multiline' => true,
'trim_array_spaces' => true,
'unary_operator_spaces' => true,
'binary_operator_spaces' => true,
'whitespace_after_comma_in_array' => true,
'single_trait_insert_per_statement' => false,
])
->setLineEnding("\n");

此套件也收錄在 PHP Productive Pack

詳細設定可以參考 List of Avaliable Rules

References