PHPStorm中使用phpcs和php-cs-fixer

前言:良好的代碼規範可以提高代碼可讀性,減少團隊溝通維護成本,所以本文嘗試PSR-2代碼規範進行代碼格式化。

使用環境:

IDE:phpstorm2018.1

插件:phpcs和php-cs-fixer

 

phpcs 主要對 PHP、Java、CSS 文件定義了一系列代碼規範標準

對於 phpcs 的使用,主要有兩個途徑:

  • 在本地開發過程中,實時對我們的代碼進行檢測,讓代碼提交版本庫時,就已經符合規範標準了
  • 在服務器對提交的代碼進行檢測,如果不符合標準的,則不入代碼庫(svn可設置),打回要求修改。

安裝phpcs

composer global require squizlabs/php_codesniffer

php-cs-fixer 是一個開源的 PSR 編碼規範的格式化工具。編碼規範的出現,也促生了相應的格式化工具,可能僅需一條命令,你的代碼就可以符合編碼規範,也就成了編碼風格的最佳實踐,也就是說,在編碼的過程中你可以不必糾結於編碼中排版、縮進等等繁瑣的約束,而開心愉悅編碼。

 

安裝php-cs-fixer

composer require friendsofphp/php-cs-fixer

安裝完成了,你在vendor/friendsofphp/php-cs-fixer 下會發現一個 .php_cs.dist 文件,它是默認的格式化配置,將其複製到項目根目錄下。然後將composer加到環境變量

 

安裝symfony2

composer require escapestudios/symfony2-coding-standard

symfony2將編碼標準添加到php_codesniffer安裝路徑

/path/to/phpcs --config-set installed_paths /path/to/Symfony2-coding-standard

檢查已安裝的“symfony”編碼標準

phpcs -i

只顯示error級別報錯

phpcs -n D:\www\my-service\src\Command\BdAsrToMqCommand.php

檢查單個文件標準

C:\Users\admin\vendor\bin\phpcs D:\www\my-service\src\Command\BdAsrToMqCommand.php


 自動修復:  

C:\Users\admin\vendor\bin\phpcbf D:\www\my-service\src\Command\BdAsrToMqCommand.php

PhpStorm設置

● 步驟1:打開PhpStorm點擊 File->Settings
● 步驟2:接着點擊Languages & Frameworks->PHP->Code Sniffer點擊Configuration右側的按鈕,
● 步驟3:選擇PHP Code Sniffer (phpcs) path:的路徑,就是剛纔composer之後生成的那個phpcs.bat的路徑。
● 步驟4:選擇之後點擊Validate驗證成功
● 步驟5:節點點擊Editor->Inspections展開點擊右側的PHP
● 步驟6:勾選PHP Code Sniffer Validation 選擇右側的symfony
● 步驟7:點擊驗證成功 大功告成!!

 

設置PHPStorm php-cs-fixer操作菜單項

 

name 填寫php-cs-fixer

program需要填寫php-cs-fixer的可執行文件地址,C:\Users\用戶名\Roaming\Composer\composer\vendor\bin\php-cs-fixer.bat,linux和mac上是~/.composer/vendor/bin/php-cs-fixer

Arguments/parameters填

fix "$FileDir$/$FileName$" --config=$ProjectFileDir$/.php_cs --using-cache=no

規則可以查看 php-cs-fixer 的官方文檔。working directory填$ProjectFileDir$

設置PHPStorm php-cs-fixer操作菜單項 

 

先查看php-cs-fixer的版本號,在去官網添加對應的規則。新的版本號會添加更多規則。

參考配置 https://packagist.org/packages/fabpot/php-cs-fixer#v2.14.2

'single_quote'  => true, //簡單字符串應該使用單引號代替雙引號;
'no_unused_imports' => true, //刪除沒用到的use
'no_singleline_whitespace_before_semicolons' => true, //禁止只有單行空格和分號的寫法;
'self_accessor'             => true, //在當前類中使用 self 代替類名;
'no_empty_statement' => true, //多餘的分號
'no_extra_consecutive_blank_lines' => ['extra'], //多餘空白行
'no_blank_lines_after_class_opening' => true, //類開始標籤後不應該有空白行;
'include' => true, //include 和文件路徑之間需要有一個空格,文件路徑不需要用括號括起來;
'no_trailing_comma_in_list_call'  => true, //刪除 list 語句中多餘的逗號;
'no_leading_namespace_whitespace' => true, //命名空間前面不應該有空格;
'array_syntax'  => array('syntax' => 'short'), //數組 【】 php版本大於5.4;
'no_blank_lines_after_phpdoc' => true, //PHP 文檔塊開始開始元素下面不應該有空白行;
'object_operator_without_whitespace' => true, //(->) 兩端不應有空格;
'phpdoc_indent'             => true, //phpdoc 應該保持縮進;
'phpdoc_no_access'          => true, //@access 不應該出現在 phpdoc 中;
'phpdoc_no_package'         => true,
'phpdoc_scalar'             => ['boolean', 'double', 'integer', 'real', 'str'], //phpdoc 標量類型聲明時應該使用 int 而不是 integer,bool 而不是 boolean,float 而不是 real 或者 double;
'phpdoc_to_comment'         => true, //文檔塊應該都是結構化的元素;
'phpdoc_trim'               => true,
'phpdoc_no_alias_tag'       => array('type' => 'var'),// @type 需要使用 @var 代替;
'phpdoc_var_without_name'   => true, //@var 和 @type 註釋中不應該包含變量名;
'no_leading_import_slash'   => true, //刪除 use 前的空行;
'no_trailing_comma_in_singleline_array' => true, //PHP 單行數組最後一個元素後面不應該有空格;
'single_blank_line_before_namespace' => true,//命名空間聲明前應該有一個空白行;
'binary_operator_spaces'    => array('align_equals' => true,'align_double_arrow' => true), //等號 => 對齊   symfony是不對齊的
'cast_spaces'   =>   true, //變量和修飾符之間應該有一個空格;
'standardize_not_equals' => true, //使用 <> 代替 !=;
'concat_space' => array('spacing' => 'one'), //點連接符左右兩邊有一個的空格;symfony是沒空格
'ternary_operator_spaces'   => true, //三元運算符之間的空格標準化
'trim_array_spaces' => true, //數組需要格式化成和函數/方法參數類似,上下沒有空白行;
'unary_operator_spaces' => true, //一元運算符和運算數需要相鄰;
'no_whitespace_in_blank_line' => true, //刪除空白行中多餘的空格;
'no_multiline_whitespace_before_semicolons' => true, //分號前的空格

 配置存項目根目錄.php_cs即可

<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <[email protected]>
 *     Dariusz Rumiński <[email protected]>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

$header = <<<'EOF'
This file is part of PHP CS Fixer.

(c) Fabien Potencier <[email protected]>
    Dariusz Rumiński <[email protected]>

This source file is subject to the MIT license that is bundled
with this source code in the file LICENSE.
EOF;

$finder = PhpCsFixer\Finder::create()
    ->exclude('tests/Fixtures')
    ->in(__DIR__)
;

if (PHP_VERSION_ID < 70000) {
    $finder
        ->notPath('tests/Test/Constraint/SameStringsConstraintForV7.php')
        ->notPath('tests/Test/Constraint/XmlMatchesXsdConstraintForV7.php')
    ;
}

$config = PhpCsFixer\Config::create()
    ->setRiskyAllowed(true)
    ->setRules([
        '@Symfony' => true,
        '@Symfony:risky' => true,
        '@PHPUnit48Migration:risky' => true,
        'php_unit_no_expectation_annotation' => false,
        'protected_to_private' => false,
        'native_function_invocation'=>false,  //在系統函數前添加\以加快解析速度\count($list)
        'phpdoc_separation' => true,
        'trim_array_spaces' => false,
        'single_quote'=>false,
        'modernize_types_casting'=>false //使用相應的類型轉換運算符替換intval、floatval、doubleval、strval和boolval函數調用。
    ])
    ->setFinder($finder)
;

// special handling of fabbot.io service if it's using too old PHP CS Fixer version
if (false !== getenv('FABBOT_IO')) {
    try {
        PhpCsFixer\FixerFactory::create()
            ->registerBuiltInFixers()
            ->registerCustomFixers($config->getCustomFixers())
            ->useRuleSet(new PhpCsFixer\RuleSet($config->getRules()));
    } catch (PhpCsFixer\ConfigurationException\InvalidConfigurationException $e) {
        $config->setRules([]);
    } catch (UnexpectedValueException $e) {
        $config->setRules([]);
    } catch (InvalidArgumentException $e) {
        $config->setRules([]);
    }
}

return $config;

 對PHP文件進行檢查:phpstorm點擊Tools->External Tools->php-cs-fixer

 

PHP升級代碼兼容

當我們進行PHP版本升級的時候,比如從5.x升級到7.x會遇到項目代碼不兼容的情況。如果通過人工檢查,工作量比較大,我們可以使用PHPCompatibility+PHP_CodeSniffer進行兼容性檢查

path/to/phpcs --config-set installed_paths path/to/PHPCompatibility 

一些常用參數

phpcs --standard=PHPCompatibility --runtime-set testVersion 7.2 --report=summary --extensions=php [path]

  • --runtime-set <option> <value> 可設置檢查PHP版本
  • --report=summary 報表模式
  • --extensions=php 設定檢查文件後綴名

as

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章