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

ggazkfy8  于 2023-04-28  发布在  PHP
关注(0)|答案(3)|浏览(170)

我目前使用的是VS Code的最新版本1。41.1(在编写本报告时)。
我安装了PHP CS Fixer来自动格式化我的代码。但是有一个行为我不喜欢。它总是这样格式化代码:

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

但这并没有给我很好的可读性。
我想做到这一点:

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

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

hl0ma9xz

hl0ma9xz1#

根据@Nicolas的评论,我可以通过两个步骤来实现它。
1.我必须在项目的根目录下创建一个名为.php_cs的文件
1.将此代码块添加到文件中:

<?php

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

一切都完成了,工作起来就像一个魅力。谢谢你的帮助@Nicolas!

pcww981p

pcww981p2#

也在找同样的东西。我尝试了Radical_activity给出的(接受的)答案,但对我不起作用。在这里找到了另一个片段:
https://stackoverflow.com/a/54883745/4638682

片段:

<?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文件。这对我很有效!

bxfogqkk

bxfogqkk3#

现在天数:

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

相关问题