安裝 PHP_CodeSniffer
安裝 phpcs
phpcs 是 PHP 代碼規范的檢測工具。
# 下載 $ curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar # 加入到命令目錄 $ mv phpcs.phar /usr/local/bin/phpcs # 賦予執行權限 $ sudo chmod +x /usr/local/bin/phpcs # 檢驗是否成功 $ phpcs -h
安裝 phpcbf
phpcbf 是 PHP 代碼規范的修復工具。
# 下載 $ curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcbf.phar # 加入到命令目錄 $ mv phpcbf.phar /usr/local/bin/phpcbf # 賦予執行權限 $ sudo chmod +x /usr/local/bin/phpcbf # 檢驗是否成功 $ phpcbf -h
使用 phpcs
phpcs 配置
1.查看詳細配置。使用命令: phpcs --config-show (下面是我當前的配置)
colors: 1 default_standard: PSR2 encoding: utf-8 error_severity: 1 ignore_errors_on_exit: 1 ignore_warnings_on_exit: 1 report_format: summary report_width: auto severity: 1 show_progress: 1 show_warnings: 1 tab_width: 4 warning_severity: 8
2.設置默認的編碼標准。(這個很重要,建議使用 PSR2 的標准)
# 查看配置 $ phpcs -i The installed coding standards are MySource, PEAR, PHPCS, PSR1, PSR2, Squiz and Zend # 設置編碼標准為 PSR2 $ phpcs --config-set default_standard PSR2
3.隱藏警告。(當然,對於強迫症來說,警告都是不允許的,非強迫症患者可以使用此配置項)
# 隱藏警告提醒 $ phpcs --config-set show_warnings 0 # 開啟警告提醒 $ phpcs --config-set show_warnings 1
4.顯示檢查進程。(如果項目需要檢查的文件較多可以開啟這個)
# 顯示檢查進程 $ phpcs --config-set show_progress 1 # 關閉進程顯示 $ phpcs --config-set show_progress 0
5.顯示顏色。 (給自己點顏色看看哈)
# 顯示顏色 $ phpcs --config-set colors 1 # 關閉顏色顯示 $ phpcs --config-set colors 0
6.修改錯誤和警告等級
# 顯示所有的錯誤和警告 $ phpcs --config-set severity 1 # 顯示所有的錯誤,部分警告 注意等級可有從 5-8 5 的警告顯示會更多,8 的更少 $ phpcs --config-set severity 1 $ phpcs --config-set warning_severity 5
7.設置默認編碼
# 設置 utf-8 $ phpcs --config-set encoding utf-8
8.設置 tab 的寬度
# tab 為 4 個空格 $ phpcs --config-set tab_width 4 # 也可以對單獨文件生效 $ phpcs --tab-width=0 /path/to/code
代碼驗證
1.校驗單個文件
# 校驗單個文件 $ phpcs filename
2.校驗目錄(如:整個項目)
# 校驗目錄 注意這個時候別因為 linux 學的太好加個 -R 哈。 $ phpcs /path/dir
結果分析
結果展現的形式:
full, xml, checkstyle, csv, json, emacs, source, summary, diff, svnblame, gitblame, hgblame or notifysend
指定展現形式:
# 匯總的形式 phpcs --report=summary test01.php # json 形式 (個人覺得這個形式更清晰) phpcs --report=json test01.php
修復代碼
使用 phpcbf
覆蓋式修復
# 直接覆蓋 $ phpcbf /path/code
生成中間文件
# 生成新文件 $ phpcbf /path/to/code --suffix=.fixed
使用 diff
# 以 test.php 為例 會生成 test.php.diff 文件 $ phpcs --report-diff=test.php.diff test01.php