[强迫症福利] 使用 PHPStorm 对齐数组的键值对

在 PHPStorm 中定义数组时往往会写成下面这样:

    public function index()
    {
        return [
            'foo' => 'bar',
            'foo-bar' => 'foo-bar',
            'f' => 'b'
        ];
    }

这时就有一群强迫症跳出来说这个组数的键值怎么没对齐、怎么没有尾随逗号、太丑了不能看。。这时更改 PHPStorm 中的一些设置项,便可达到下面的效果:

    public function index()
    {
        return [
            'foo'     => 'bar',
            'foo-bar' => 'foo-bar',
            'f'       => 'b',
        ];
    }

设置步骤

打开 Settings -> Editor -> PHP -> Warpping and Braces,找到 Array itializer -> Align key-value paipars 并勾选、保存,那么在使用 Ctrl + Alt + L 格式化代码时便会自动对齐数组的键值对:

[PHPStorm] 格式化代码时对其数组

此外建议在 Code Conversion 中勾选这两项:

[PHPStorm] 格式化代码时对其数组

在格式化时这两项分别会强制使用数组短语法、最后一个元素自动尾随一个逗号。

PS:注意低版本的 PHPStorm 中 以上配置项的位置可能会不同,可在搜索框中直接输入配置项的名称来定位。

本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 4年前 自动加精
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 14

感觉对齐并不好看,我曾经也是喜欢这样,后来越看越觉得不好看了,看各种开源项目也放弃这个对齐样式了

4年前 评论
田勇 4年前
varro (楼主) 4年前
月光 4年前
overtrue (作者) 4年前

这个感觉可以写一个系列出来。

4年前 评论
varro (楼主) 4年前

感觉对齐不好看了

4年前 评论

我主要觉得,,,对齐的话, 只能依赖工具来对齐, 没人会手打对齐吧,,,

4年前 评论

补充一下。mac电脑用户Ctrl一定要换成Commend键哦!否则。你一直对不齐的哦! :blush:

4年前 评论

幸好我强迫症是写代码一定要按照各个语言的最佳规范 :joy:

4年前 评论

还好我没有这个强迫症

4年前 评论
TimJuly

对齐是一种错误的做法,尤其在多人协作项目中

千万不要对齐!!!

4年前 评论

也就是刚开始码的时候, 有那个强迫症和新鲜劲, 才format code!
现在我就对自己讲: 您这样真没必要

            $this->values = array(
                'out_trade_no' => $findOrder->out_orderid,
                'money' => $findOrder->order_amount,
                'trade_status' => 'TRADE_SUCCESS',
            );
4年前 评论

数组知道了.

请问如何对其初始化的变量呢. :blush:

4年前 评论

php_cs


<?php
$header
       = <<<EOF
What samego team is that is 'one thing, a team, work together'
Value comes from technology, technology comes from sharing~
EOF;
$rules = array(
    '@Symfony'                                   => true,
    'header_comment'                             => array('header' => $header),
    'array_syntax'                               => array('syntax' => 'short'),
    'ordered_imports'                            => true, // 按顺序use导入
    'no_useless_else'                            => true, // 删除没有使用的else节点
    'no_useless_return'                          => true, // 删除没有使用的return语句
    'php_unit_construct'                         => true,
    'single_quote'                               => true, //简单字符串应该使用单引号代替双引号
    'no_unused_imports'                          => true, //删除没用到的use
    'no_singleline_whitespace_before_semicolons' => true, //禁止只有单行空格和分号的写法
    'self_accessor'                              => true, //在当前类中使用 self 代替类名
    'no_empty_statement'                         => true, //多余的分号
    'no_whitespace_in_blank_line'                => true,
    'binary_operator_spaces'                     => ['default' => 'align_single_space'] //等号对齐、数字箭头符号对齐
);
return PhpCsFixer\Config::create()
                        ->setRiskyAllowed(true)
                        ->setRules($rules)
                        ->setFinder(
                            PhpCsFixer\Finder::create()
                                             ->exclude('vendor')
                                             ->in(__DIR__)
                        );
4年前 评论
xiaoniuge

用 php-cs-fixer 自动格式化,一个配置配合 Git 自动格式化,补充楼上。

示例 Git Hook

忽略前端的代码格式化,修改一下就可以用。

#!/bin/bash
#
# check PHP code syntax error and standard with phpcs
# https://blog.csdn.net/xsgnzb/article/details/52222366?locationNum=4&fps=1
# https://blog.csdn.net/ljihe/article/details/80826071
# =================== how to use ====================
# cp ./build/pre-commit.sh ./.git/hooks/pre-commit
# chmod 777 ./.git/hooks/pre-commit
# git commit -h
# git commit -n -m 'pass hook' #bypass pre-commit and commit-msg hooks
# ==================== end ==========================

PROJECT=$(git rev-parse --show-toplevel)
cd $PROJECT
SFILES=$(git diff --cached --name-only --diff-filter=ACMR HEAD | grep \\.php$)

# Determine if a file list is passed
if [ "$#" -ne 0 ]
then
    exit 0
fi

echo "Checking PHP Lint..."

for FILE in $SFILES
do
    php -l -d display_errors=0 $FILE
    if [ $? != 0 ]
    then
        echo "Fix the php error before commit."
        exit 1
    fi
    FILES="$FILES $PROJECT/$FILE"
done

phpcsfixer_path=$(cd `dirname $0`; pwd)"/../../build/php-cs-fixer"
gulp_path=$(cd `dirname $0`; pwd)"/../../frontend/node_modules/.bin/gulp"
prettier_path=$(cd `dirname $0`; pwd)"/../../frontend/node_modules/.bin/prettier"

# format code style
if [ "$FILES" != "" ]
then
    echo "Running Code Sniffer..."

    isCheck=""

    for FILE in $SFILES
    do

        IGNORE_PATH=(
            'vendor'
        )

        for IGNORE_ITEM in ${IGNORE_PATH[@]}
        do
            if [[ ${FILE} =~ ${IGNORE_ITEM} ]]
            then
                echo "Ignore file of "${IGNORE_ITEM}
                continue 2
            fi 
        done

        #result=`~/.composer/vendor/bin/php-cs-fixer fix $FILE --config=.php_cs.dist`
        #result=`php-cs-fixer fix $FILE --config=.php_cs.dist`
        result=`php $phpcsfixer_path fix $FILE --config=.php_cs.dist`

        if [ "$result" != "" ]
        then
            echo $result
            isCheck=$result
            git add $FILE
        fi
    done

    if [ "$isCheck" != "" ]
    then
        echo "The file has been automatically formatted."
    fi
fi

# for js
jsfiles=$(git diff --cached --name-only --diff-filter=ACM "*.js" "*.jsx" "*.vue" "*.css" "*.less" | tr '\n' ' ')
[ -z "$jsfiles" ] && exit 0

# format iview
$gulp_path iview --gulpfile frontend/gulpfile.js

# Prettify all staged .js files
echo "$jsfiles" | xargs $prettier_path --config frontend/.prettierrc.js --ignore-path frontend/.prettierignore --write

# Add back the modified/prettified files to staging
echo "$jsfiles" | xargs git add

git update-index -g

exit $?
4年前 评论

对齐留太多的空格,反而不喜欢。看一个变量的值,还得跳过好多空格才能看到,麻烦。

4年前 评论

file 请问 这种 不在数据里的 如何对齐呢 快捷键 不生效

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!