4

I'm currently using VS Code's latest version 1.41.1 (at the time of writing).

I've installed PHP CS Fixer to auto-format my code. 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? Or is there any option in PHP CS Fixer to skip formatting these curly brackets? Any other otpions?

Gama11
  • 31,714
  • 9
  • 78
  • 100
Radical_Activity
  • 2,618
  • 10
  • 38
  • 70
  • 4
    let's say this is highly debatable. There is an option to pass a config file with rules to your extension. Maybe there is a [rule here](https://cs.symfony.com/) that would do what you are looking for. – Nicolas Jan 16 '20 at 12:51
  • Also, you don't need php-cs to format code in Visual Studio Code - just mark the code you want to format, CTRL+K + CTRL+F. But please just use PSR2 like everyone else ;) – WoodyDRN Jan 16 '20 at 13:33

3 Answers3

6

Based on @Nicolas's comment I was able to make it work in 2 steps.

  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',
        )
    ));
    

All done and works like a charm. Thanks for the help @Nicolas!

Radical_Activity
  • 2,618
  • 10
  • 38
  • 70
0

Was looking for the same thing. I tried the (accepted) answer Radical_activity gave, but that didn't work for me. Found this another snippets here:

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. That worked for me!

Loosie94
  • 574
  • 8
  • 17
0

Now days:

'control_structure_braces' => true,
'control_structure_continuation_position' => [
    'position' => 'next_line'
],
Anuga
  • 2,619
  • 1
  • 18
  • 27