如何在 VS Code 中自动将 PHP 代码花括号格式化为新行

4

我目前正在使用VS Code最新版本1.41.1(在撰写本文时)。

我已安装了PHP CS Fixer来自动格式化我的代码。但是有一种行为我不喜欢。它总是将代码格式化为以下形式:

if (condition) {
    // code...
} else {
    // code
}

但这样并不能让我获得良好的可读性。

我希望达到以下效果:

if (condition)
{
    // code...
}
else
{
    // code
}

有没有VS Code支持PHP代码格式化的扩展?或者在PHP CS Fixer中跳过这些大括号的格式化选项?还有其他选择吗?

4
我们可以说这是一个极具争议的问题。你有一个选项可以通过传递一个带有规则的配置文件给你的扩展程序。也许在这里有一个规则可以实现你想要的功能。 - Nicolas
此外,在 Visual Studio Code 中,您不需要使用 php-cs 来格式化代码 - 只需标记要格式化的代码,然后按下 CTRL+K + CTRL+F 即可。但请像其他人一样使用 PSR2 ;) - WoodyDRN
3个回答

6

根据@Nicolas的评论,我成功地分成了两步。

  1. I had to create a file in the root of my project with a name of .php_cs
  2. Add this block of code to the file:

    <?php
    
    return PhpCsFixer\Config::create()
    ->setRules(array(
        'braces' => array(
            'position_after_anonymous_constructs' => 'next',
            'position_after_control_structures' => 'next',
        )
    ));
    

所有工作都完成得非常好。感谢 @Nicolas 提供的帮助!


1
很高兴能帮忙! - Nicolas

1

现在的日子:

'control_structure_braces' => true,
'control_structure_continuation_position' => [
    'position' => 'next_line'
],

0

我也在寻找同样的东西。我尝试了Radical_activity提供的(被接受的)答案,但对我没有用。在这里找到了另外一些代码片段:

https://dev59.com/Ea_la4cB1Zd3GeqPzdxo#54883745

代码片段:

<?php

$finder = PhpCsFixer\Finder::create()
    //->exclude('somedir')
    //->notPath('src/Symfony/Component/Translation/Tests/fixtures/resources.php'
    ->in(__DIR__)
;

return PhpCsFixer\Config::create()
    ->setRules([
        '@PSR2' => true,
        'strict_param' => false,
        'array_syntax' => ['syntax' => 'long'],
        'braces' => [
            'allow_single_line_closure' => true, 
            'position_after_functions_and_oop_constructs' => 'same'],
    ])
    ->setFinder($finder)
;

你还需要在代码库中创建一个.php_cs文件。

这对我很有用!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接