美文网首页
代码格式化工具使用介绍

代码格式化工具使用介绍

作者: 爱吃秋葵的莫冲 | 来源:发表于2018-07-27 12:07 被阅读78次

为什么要使用代码规范工具

  • 代码审查是软件工程的最佳实践
  • 代码规范需要反复强调
  • 太多时间浪费在审核格式上而不是代码本身
  • 这工作应该让机器来做
  • 规范的价值在于:整齐划一,而不是完美

PHP Coding Standards Fixer 简介

  • 作者:Fabien Potencier,creator of Symfony/PHP-FIG
  • 开源:MIT license.
  • defined in the PSR-optional parameters
  • 环境要求:php5.6 以上版本

使用介绍

安装

$ composer global require friendsofphp/php-cs-fixer
$ export PATH="$PATH:$HOME/.composer/vendor/bin"(这是临时变量,需要加入系统全局变量,并赋予www-data 用户权限)
$ php-cs-fixer self-update  (for PHAR)
composer update php-cs-fixer

使用

$ php-cs-fixer fix /path/to/dir  fix 指定目录
$ php-cs-fixer fix /path/to/file fix 指定文件
$ php-cs-fixer fix /path/to/project --rules=@PSR2 使用 PSR2 规范fix
$ php-cs-fixer fix /path/to/code --dry-run 显示需要fix的文件,不修改文件内容
php-cs-fixer fix --config=.php_cs.dist -v 基于配置文件fix
cat foo.php | php php-cs-fixer.phar fix foo.php --diff - 对比 fix 前后的文件内容

代码格式化原理

Tokenizer
token_get_all

配置说明

  • 'array_syntax' => ['syntax' => 'short'], 数组定义方式(array() or []),默认 long(array())
  • 'binary_operator_spaces'=>['align_double_arrow' => true, 'align_equals' => true],
    align_double_arrow (false, null, true): whether to apply, remove or ignore double arrows alignment; defaults to false 双箭头对齐
  • align_equals (false, null, true): whether to apply, remove or ignore equals alignment; defaults to false 等号对其
  • 'combine_consecutive_unsets' => true, Calling unset on multiple items should be done in one call.
  • 'concat_space'=> ["spacing"=> "one"] Concatenation should be spaced according configuration. 默认none,demo:'a'.'b',one:'a' . 'b'
  • 'header_comment' => ['header' => $header],Add, replace or remove header comment. 类文件注释
  • 'no_short_echo_tag' => true, Replace short-echo <?= with long format <?php echo syntax.
  • 'blank_line_before_return'=>true, return 前空一行
  • 'no_useless_return' => true, There should not be an empty return statement at the end of a function.
  • 'ordered_class_elements' => true, 类元素排序
  • 'ordered_imports' => true,use 语句排序
  • 'phpdoc_add_missing_param_annotation' => true, phpdoc 添加缺失的注解
  • 'no_trailing_comma_in_list_call'=>true,单行数组删除最后一个逗号
  • 'strict_comparison' => false,严格比较

完整的配置说明及示例请查看php-cs-fixer-configurator

输出码说明

  • 0 OK.
  • 1 General error (or PHP minimal requirement not matched).
  • 4 Some files have invalid syntax (only in dry-run mode).
  • 8 Some files need fixing (only in dry-run mode).
  • 16 Configuration error of the application.
  • 32 Configuration error of a Fixer.
  • 64 Exception raised within the application.
    (applies to exit codes of the fix command only)

相关文章

网友评论

      本文标题:代码格式化工具使用介绍

      本文链接:https://www.haomeiwen.com/subject/jdbdfxtx.html