php代碼格式化工具 php-cs-fixer的使用

php-cs-fixer簡介

php-cs-fixer 是個代碼格式化工具,格式化的標準是 PSR-一、PSR-2 以及一些 symfony 的標準。php

安裝

官方網站 github
有兩個版本 v1 和 v2 ,其中 v1 須要php 5.3.6 版本以上, v2 須要 php 5.6 版本以上。升級說明
你能夠直接下載最新版本封裝好的 phar 包:php-cs-fixer.phar
如下都是以v2版本爲例子git

unix:github

wget http://cs.sensiolabs.org/download/php-cs-fixer-v2.phar -O php-cs-fixer
chmod a+x php-cs-fixer
mv php-cs-fixer /usr/local/bin/php-cs-fixer

windowsvim

下載php-cs-fixer
把php-cs-fixer 放入php目錄,而後把php安裝目錄加入系統PATH變量

使用

/usr/local/bin/php-cs-fixer

輸入圖片說明

fix就是最基本的命令windows

# 格式化某個目錄
php-cs-fixer fix /path/to/dir
# 格式化某個文件
php-cs-fixer fix /path/to/file

--rules 選項用於對項目或者文件的規則控制:編輯器

php-cs-fixer fix /path/to/file
php-cs-fixer fix /path/to/project --rules=@PSR2
php-cs-fixer fix /path/to/dir --rules=line_ending,full_opening_tag,indentation_type
php-cs-fixer fix /path/to/dir --rules=-full_opening_tag,-indentation_type,-@PSR1

默認狀況下執行的是 PSR-1 和 PSR-2 的全部選項
rules 後面支持逗號(,),減號(-)增長規則和排除多個規則
更多使用方式 手冊ide

項目實踐

通常在團隊開發項目中,會經過一個配置來保證代碼質量,在項目根目錄添加一個 .php_cs 文件的方式實現。 下面是一個例子工具

$finder = PhpCsFixer\Finder::create()
    ->files()
    ->name('*.php')
    ->exclude('vendor')
    ->in(__DIR__)
    ->ignoreDotFiles(true)
    ->ignoreVCS(true);
$fixers = array(
    '@PSR2' => true,
    'single_quote'  => true, //簡單字符串應該使用單引號代替雙引號;
    'no_unused_imports' => true, //刪除沒用到的use
    'no_singleline_whitespace_before_semicolons' => true, //禁止只有單行空格和分號的寫法;
    'self_accessor'             => true, //在當前類中使用 self 代替類名;
    'binary_operator_spaces'    => true, //二進制操做符兩端至少有一個空格;
    'no_empty_statement' => true, //多餘的分號
    'no_extra_consecutive_blank_lines' => true, //多餘空白行
    'no_blank_lines_after_class_opening' => true, //類開始標籤後不該該有空白行;
    'include' => true, //include 和文件路徑之間須要有一個空格,文件路徑不須要用括號括起來;
    'no_trailing_comma_in_list_call'  => true, //刪除 list 語句中多餘的逗號;
    'no_leading_namespace_whitespace' => true, //命名空間前面不該該有空格;
    'standardize_not_equals' => true, //使用 <> 代替 !=;
   );
return PhpCsFixer\Config::create()
    ->setRules($fixers)
    ->setFinder($finder)
    ->setUsingCache(false);

編輯器插件

手動對代碼文件fix效率仍是比較低的,因此仍是須要自動化,經常使用的ide的插件網站

  • Atom (設置->安裝->搜索 atom-beautify) 如下步驟以 atom-beautify 0.30.5 爲例
    • atom-beautify打開設置中的Executables 找到 PHP-CS-Fixer 輸入 php-cs-fixer 的 完整路徑
    • atom-beaufity 的 php 選項的 Deault beautifier 設置中選擇 PHP-CS-Fixer 並打開 Beautify On Save選項
    • PHP-CS-Fixer VERSION 選擇 2
    • 其它選項都默認,這樣設置的話,就會默認遵循根目錄下的.php_cs 規則了
  • NetBeans (工具->插件->可用插件->搜索CS Fixer)
  • Vim

參考文檔

php-cs-fixeratom

相關文章
相關標籤/搜索