跳转至

php_codesniffer


2016-12-14 by dongnan

目标

使用 php_codesniffer 配合 git hooks(钩子) ,在提交 php代码时,对代码进行规范检查,不符合规范的代码不能提交。

这个功能需要两个组件:

  • php_codesniffer
  • git hooks 钩子。

简介

PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.

安装请参考这篇文章

举个栗子

使用 php_codesnifferphp 代码检查示例。

不符合规范

phpcs test.php
FILE: /root/test.php
----------------------------------------------------------------------
FOUND 6 ERRORS AND 1 WARNING AFFECTING 2 LINES
----------------------------------------------------------------------
4 | ERROR   | Doc comment short description must start with a
|         | capital letter
5 | WARNING | PHP version not specified
5 | ERROR   | Missing @category tag in file comment
5 | ERROR   | Missing @package tag in file comment
5 | ERROR   | Missing @author tag in file comment
5 | ERROR   | Missing @license tag in file comment
5 | ERROR   | Missing @link tag in file comment
----------------------------------------------------------------------
Time: 52ms; Memory: 3.25Mb

shell 退出状态 1 不成功

echo $?
1

符合规范

按照提示修改测试文件

cat /root/test.php
<?php

/**
* PHP version 5
*
* @category  PHP
* @package   PHP_CodeSniffer
* @author    Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)
* @license   ywwd.net Licence
* @link      http://pear.php.net/package/PHP_CodeSniffer
*/

echo phpinfo();

shell 退出状态 0 成功

phpcs test.php  && echo $?
0

参考

更详细资料请参考: PHP_CodeSniffer 项目

回到页面顶部