php-cs-fixer : keep brace on the same line of function declaration

8k views Asked by At

Php cs fixer is doing :

function foobar()
{
....
}

and I want:

function foobar() {
....
}

I can't see what is the config to keep braces on the same line in my config .php_cs file, nor on https://github.com/FriendsOfPHP/PHP-CS-Fixer. I'm using php-cs-fixerV2.

My config file: https://pastebin.com/v03v9Lb5

2

There are 2 answers

5
scrowler On BEST ANSWER

You have PSR-2 enabled, which requires the braces on the next line. From the documentation it looks like you can set braces.position_after_functions_and_oop_constructs to same (default would be next):

  • position_after_functions_and_oop_constructs ('next', 'same'): whether the opening brace should be placed on “next” or “same” line after classy constructs (non-anonymous classes, interfaces, traits, methods and non-lambda functions); defaults to 'next'

myconfig.php_cs:

    'braces' => array(
        'allow_single_line_closure' => true,
        'position_after_functions_and_oop_constructs' => 'same',
    ),
2
ponsfrilus On

The style you described here is called "the one true brace style" (abbreviated as 1TBS or OTBS).

As I get the exact same problem, I've finally ended here and while @Robbie answer helps, I still needed to search a lot.

So I finally get this .php_cs in my repository:

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

Some explainations (from the (PHP-CS-Fixer README):

  • array_syntax to long means array() instead of []. Whether to use the long or short array syntax; defaults to 'long';
  • allow_single_line_closure: whether single line lambda notation should be allowed; defaults to false;
  • position_after_functions_and_oop_constructs: whether the opening brace should be placed on "next" or "same" line after classy constructs (non-anonymous classes, interfaces, traits, methods and non-lambda functions); defaults to 'next'.

In IDE such Atom, the php-cs-fixer plugin will search for the .php_cs config file in the root path of the current project. It's also possible to specify the path.

Last but not least, the website of Michele Locati, PHP CS Fixer configuration can really helps.