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的插件網站
php-cs-fixeratom