使用php-cs-fixer来格式化php代码

来源:赵克立博客 分类: PHP 标签:PHP发布时间:2017-02-06 13:51:28最后更新:2017-02-10 19:27:18浏览:5379
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2017-02-10 19:27:18
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章

文档地址

https://github.com/FriendsOfPHP/PHP-CS-Fixer

到上面地址下载php-cs-fixer.phar这个文件

新建一个格式化配置文件(使用哪些规则对代码进行格式化)

$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;
return PhpCsFixer\Config::create()
	->setRiskyAllowed(true)
	->setRules(array(
		'@Symfony'                              => true,
		'@Symfony:risky'                        => true,
		'array_syntax'                          => array('syntax' => 'long'),
		'combine_consecutive_unsets'            => true,
		// one should use PHPUnit methods to set up expected exception instead of annotations
		'general_phpdoc_annotation_remove'      => array('expectedException', 'expectedExceptionMessage', 'expectedExceptionMessageRegExp'),
		'header_comment'                        => array('header' => $header),
		'heredoc_to_nowdoc'                     => true,
		'no_extra_consecutive_blank_lines'      => array('break', 'continue', 'extra', 'return', 'throw', 'use', 'parenthesis_brace_block', 'square_brace_block', 'curly_brace_block'),
		'no_unreachable_default_argument_value' => true,
		'no_useless_else'                       => true,
		'no_useless_return'                     => true,
		'ordered_class_elements'                => true,
		'ordered_imports'                       => true,
		'php_unit_strict'                       => true,
		'phpdoc_add_missing_param_annotation'   => true,
		'phpdoc_order'                          => true,
		'psr4'                                  => true,
		'strict_comparison'                     => true,
		'strict_param'                          => true,
	))
	->setFinder(
		PhpCsFixer\Finder::create()
			->exclude('tests/Fixtures')
			->in(__DIR__)
	)
;

创建一个format_php_code.bat文件,也就是一个批处理,最后实现把php文件拖动到bat文件上就可以格式化文件

php php-cs-fixer.phar fix --config=.php_cs.dist  %~sf1
pause

这个时候当前目录里有三个文件

blob.png

随便找一个php文件拖动到format_php_code.bat上试试

想要自定义一些配置的话可以参考官方文档上的配置选项自己修改

完整的格式化php代码压缩包附件

php-cs-fixer.zip



微信号:kelicom QQ群:215861553 紧急求助须知
Win32/PHP/JS/Android/Python