简体   繁体   English

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

[英]How to auto format PHP code curly braces to new lines in VS Code

I'm currently using VS Code's latest version 1.41.1 (at the time of writing).我目前正在使用 VS Code 的最新版本 1.41.1(在撰写本文时)。

I've installed PHP CS Fixer to auto-format my code.我已经安装了 PHP CS Fixer 来自动格式化我的代码。 However there's a behavious that I don't like.然而,有一种我不喜欢的行为。 It always formats the code like this:它总是像这样格式化代码:

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

But this is not giving me good readability.但这并没有给我很好的可读性。

I'd like to achieve this:我想实现这一目标:

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

Is there any extentsion that supports this code formatting for PHP in VS Code?在 VS Code 中是否有任何扩展支持 PHP 的这种代码格式? Or is there any option in PHP CS Fixer to skip formatting these curly brackets?或者 PHP CS Fixer 中是否有任何选项可以跳过这些大括号的格式? Any other otpions?还有其他选择吗?

Based on @Nicolas's comment I was able to make it work in 2 steps.根据@Nicolas 的评论,我可以分两步完成。

  1. I had to create a file in the root of my project with a name of .php_cs我必须在我的项目的根目录中创建一个名为.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', ) ));

All done and works like a charm.一切都完成了,就像一个魅力。 Thanks for the help @Nicolas!感谢@Nicolas 的帮助!

Was looking for the same thing.正在寻找同样的东西。 I tried the (accepted) answer Radical_activity gave, but that didn't work for me.我尝试了 Radical_activity 给出的(接受的)答案,但这对我不起作用。 Found this another snippets here:在这里找到了另一个片段:

https://stackoverflow.com/a/54883745/4638682 https://stackoverflow.com/a/54883745/4638682

Snippet:片段:

<?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)
;

From which you also need to create a .php_cs file in your repository.您还需要从中创建一个.php_cs文件在您的存储库中。 That worked for me!那对我有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM