Search code examples
phpphpstormcode-formatting

PhpStorm multi line if() statement auto format


Let's assume we use PHP and hard wrap at 80 in our project.

I want this:

if ($text === 'testTestTestTestTestTestTestTestTest' || $text === 'testTestTestTestTestTestTestTestTest' || $text === 'testTestTestTestTestTestTestTestTest') {
    $text = 'test';
}

to become this:

if ($text === 'testTestTestTestTestTestTestTestTest' 
    || $text === 'testTestTestTestTestTestTestTestTest'
    || $text === 'testTestTestTestTestTestTestTestTest')
{
    $text = 'test';
}

Is there any way to configure PhpStorm so this formatting is performed when Ctrl + Alt + L is pressed?

I've tried some options in Settings - Editor - Code Style - PHP - Wrapping and Braces - 'if()' statement, but it didn't help.

Seems like I'm doing something wrong. Please, help.


Solution

  • First of all, there's a statement in PSR-12 on how you should format such type of long expressions. In our case it should be like this:

    if (
        $text === 'testTestTestTestTestTestTestTest'
        || $text2 === 'testTestTestTestTestTestTestTestTest'
        || $text3 === 'testTestTestTestTestTestTest'
    ) {
        $text = 'test';
    }
    

    To make PhpStorm format it like that:

    1. Go to File | Settings | Editor | Code Style | PHP
    2. On the right side hit "Set from..." -> PSR-12
    3. Go to Wrapping and Braces tab
    4. Set Binary expressions = Wrap if long and checkmark to Operation sign on next line
    5. On the same tab at the 'if()' statement section check both New line before first element and New line before last element.