Neo Anderson's Blog

通过IDE/编辑器/Shell 实现Php 文件自动格式化

字数统计: 453阅读时长: 1 min
2022/01/11
  • 我们建立个各种代码编码规范和格式标准,但是书写的时候避免不了手误,编写遗忘的时候. 通过工具辅助自动帮助修复无疑是一件省时省力的事情,下面就举例说一种:

单一文件的实时格式处理

环境说明
1
2
3
IDE: PhpStrom

OS: MAC-OS
依赖插件
1
2
3
4
5
plugin:

1, `brew install php-cs-fixer` 或者

2, 已经安装了git-hook集成(安装方式)的可以用本身项目bin目录下的php-cs-fix
配置流程说明:

1 , Command+, 打开preferences配置窗口.

2, 在tools 模块,打开File Watchers 选项. 点击+ 添加自定义功能组件

3, 自定义名字(不过为了统一建议都使用 php-cs-fix)

1
2
Program:   /private/var/www/work/gcu.credit/bin/php-cs-fixer (改为自己的工程安装目录)
Arguments: fix $FilePath$ -vvv --stop-on-violation --using-cache=no --show-progress=estimating

4, 勾选该设置,则开启自动化格式化过程,可以在你编辑当前文件的同时,自动帮你格式化代码.

多文件的规范问题发现与处理

场景:适用于copy代码出现大面积,大量文件的规范问题
#./app 要修复的目录
php-cs-fixer fix ./app

#mac安装方式
brew install php-cs-fixer
brew install phpcs

文件规范检测

  • 保存以下shell脚本至文件 /usr/local/bin/check_code_standard_php && 修改所有者权限
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/bin/bash

# 检查PHP编码规范
exclude_rules="^(vendor|libraries|resources|database)" # 默认不检查代码规范的目录, 可通过参数修改

if [[ ! -z $1 ]]; then
exclude_rules=$1
fi

files=`git diff --name-only origin/online|grep php$|awk '{print $NF}'|sort|uniq|grep -v -E "$exclude_rules"`
exit_code=0

for file in $files
do
if [ -f $file ]; then
phpcs --standard=PSR2 $file
return=$?
if [ $return -gt 1 ]; then
exit_code=$return
fi
fi
done

exit $exit_code

  • 运行 check_code_standard_php
  • 根据提示建议手动修复, 逐步养成编码规范习惯
CATALOG
  1. 1. 单一文件的实时格式处理
    1. 1.1. 环境说明
    2. 1.2. 依赖插件
    3. 1.3. 配置流程说明:
  2. 2. 多文件的规范问题发现与处理
  3. 3. 文件规范检测