Sidebar

x

Automated Code Specification Detection — CodeSniffer

When you see a messy project, you will definitely have a variety of /_ \, code readability is not easy to maintain. A good project should look like it's from a single person. This requires a set of code specifications to constrain, and of course the project members must be required to implement the set.

An automated PHP code specification checking tool, PHP_CodeSniffer, is recommended here. When CodeSniffer is combined with PhpStrom and Git, the automated code specification is extremely convenient and reliable.

installation
CodeSniffer supports 5 installation methods, which are installed here using the pear method. If pear is not installed locally, refer to the pear installation method. Installation:

$ wget https://pear.php.net/go-pear.phar
$ php go-pear.phar
PATH=/usr/local/pear/bin:$PATH
$ source /etc/profile

Install PHP_CodeSniffer:


$ pear install PHP_CodeSniffer-1.5.3
install ok: channel://pear.php.net/PHP_CodeSniffer-1.5.3
$ phpcs --version
PHP_CodeSniffer version 1.5.3 

After PHP_CodeSniffer is installed, the phpcs executable path is the same as pear.
Configuration
Configure the detection rules of CodeSniffer as follows:

$ phpcs --config-set encoding utf-8
$ phpcs --config-set default_standard Jumei
$ phpcs --config-show
Array
(
    [encoding] => utf-8
    [default_standard] => Jumei
) 

CodeSniffer has several code specifications including PEAR, PHPCS, PSR1, PSR2, Squiz, and Zend. The storage path is /path/to/pear/share/pear/PHP/CodeSniffer/Standards. Of course, you can also develop your own code specification (such as Jumei), implement the corresponding interface of CodeSniffer, and store it in the above path.

Code specification detection
Once everything is properly configured, code specification testing is possible.

$ phpcs /home/www/init.php
FILE: /home/www/init.php
-------------------------------------------------------------
FOUND 2 ERROR(S) AFFECTING 2 LINE(S)
-------------------------------------------------------------
  1 | ERROR | Extra newline found after the open tag
 13 | ERROR | Missing function doc comment
-------------------------------------------------------------
 

Configuring PhpStrom
After the PhpStrom has completed the CodeSniffer configuration, it is possible to check the code specification and reminder in the PhpStrom.

First, in the "Settings" -> "Code Sniffer" configuration, click on the "Configuration" item and enter the phpcs path. You can use the "Validate" button to verify that the phpcs path is correct.

Phpcs path panel
Choose phpcs path

Then, in the "Settings" -> "Inspections" configuration item, check "PHP Code Sniffer validation". To be eye-catching, you can change all Warnings to Error as shown below:

Enable validation item

Finally, you can alert the PhpStrom to code that does not conform to the specification.

Does not meet the code specification reminder

Configuration hook
In order to strictly enforce the code specification, when it is found that the code does not conform to the specification, it is not allowed to submit to the code repository, which can be implemented by configuring the hook.

Here, Mercurial is used for code management. Mercurial provides support for two hooks, Bash and Python. Bash scripts are for Linux or Mac systems, Python scripts are used for Win systems, and more examples are shown in HookExamples.

In the Hook script, both 0 and "False" are indicated as successful, and "True" and any exception are represented as failures. If you use Git to manage your code, you need to replace hg status -n with git diff --name-only.

Bash
Create an executable script called pre-commit with the following contents:

#!/bin/bash

commit_files=`hg status -n`
args='-n -s'
php_files="";
php_files_count=0;

for f in $commit_files; do
    # 未找到文件或者不是php文件
    if [[ ! -e $f || $f != *.php ]]; then
        continue;
    fi
    php_files_count=$((php_files_count+1))
    # 拼接变更的php文件
    php_files="$php_files $f"
done;
# php语法错误检测
for file in $php_files; do
    eval php -l $file
done;
# 没有php文件更新
if [[ $php_files_count -eq 0 ]]; then
    exit 0;
fi
# 忽略文件
[ -f .csignore ] && ignore_file="`tr '\n' ',' < .csignore |sed 's/,$//g'`"
[ -n $ignore_file ] && args=`echo "${args} --ignore='${ignore_file}'"`
# 异常退出码为1
eval phpcs $args $php_files


在.hg/hgrc中配置使其生效:

[hooks]
precommit.phpcs = \path\to\pre-commit
 

Note the executable permissions of the pre-commit script, otherwise execute sudo chmod +x \path\to\pre-commit to increase the executable permissions.

Python
Create a script file called pre-commit.py with the following contents:

# coding: utf8
import sys
import os
import platform

def phpcs(ui, repo, hooktype, node=None, source=None, **kwargs):
    cmd_git = "hg status -n"
    csignore_name = ".csignore"
    args = "-n -s"
    php_files = csignore_files = ''
    php_files_count = 0
    # 所有变更的文件
    for item in os.popen(cmd_git).readlines() :
        item = item.strip()
        if item.find("php") == -1 or not os.path.isfile(item) :
            continue
        # php语法检测
        php_syntax = os.popen("php -l %s" % (item)).read()
        if php_syntax.find("No syntax errors") == -1 :
            ui.warn(php_syntax)
        # 待phpcs检测的文件
        php_files = php_files + " " + item
        php_files_count = php_files_count + 1
    # 忽略文件
    if os.path.isfile(csignore_name) :
        for item in open(csignore_name).readlines() :
            csignore_files = csignore_files + "," + item.strip()
    csignore_args = "--ignore='%s'" % (csignore_files.strip(','))
    if php_files_count > 0 :
        cmd_phpcs = "phpcs %s %s %s" % (args, csignore_args, php_files)
        msg = os.popen(cmd_phpcs).read().strip('.\r\n')
        if msg != '' :
            ui.warn(msg + "\r\n")
            return True
    return False
    

    
在.hg/hgrc配置使其生效:

[hooks]
precommit.phpcs = python:C:\path\to\pre-commit.py:phpcs
 

Intercepting effect
When submitting a code that does not conform to the specification, the interception effect is as follows:

FILE: \home\www\init.php
---------------------------------------------------------
FOUND 1 ERROR(S) AFFECTING 1 LINE(S)
---------------------------------------------------------
 12 | ERROR | Missing function doc comment
    |       | (Jumei.Commenting.FunctionComment.Missing)
---------------------------------------------------------
abort: precommit.phpcs hook failed 
What is cron? Perform tasks with cron timing
top 5 Free Open Source Web Hosting Control Panels
 

Comments

No comments made yet. Be the first to submit a comment
Already Registered? Login Here
Guest
Sunday, 16 December 2018