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

PHPStorm中使用phpcs和php-cs-fixer
检查单个文件标准

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

PHPStorm中使用phpcs和php-cs-fixer
 自动修复:  

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操作菜单项
PHPStorm中使用phpcs和php-cs-fixer
 

PHPStorm中使用phpcs和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操作菜单项 
PHPStorm中使用phpcs和php-cs-fixer
 

先查看php-cs-fixer的版本号,在去官网添加对应的规则。新的版本号会添加更多规则。
PHPStorm中使用phpcs和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 <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * 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 <fabien@symfony.com>
    Dariusz Rumiński <dariusz.ruminski@gmail.com>

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

相关推荐