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);