Search code examples
phpphpstormphpcodesniffer

PSR2 code style and PHP Code Sniffer doesn't agreed?


I have setup my editor code style setup from Editor > Code Style > PHP as Predefined Style >PSR1/PSR2. I have PHP Code Sniffer and PHP Mess Detector installed and configured as well. Any time I format the code using CTRL+ALT+L I get the following issue:

enter image description here

Why is that? The original code looks like (I think is not so helpful but anyway here it's):

public function myTestFunction()
{
    $is_valid = true;

    if ($this->manual_value && !$this->_InputValidator->isValidString(
            $this->manual_value,
            1,
            2,
            Regex::STRING
        )
    ) {
        $is_valid = false;
    }

    return $is_valid;
}

Solution

  • PSR2 doesn't actually say that a multi-line IF condition needs to be indented, but PHPStorm is obviously putting in 1 indent because your lines are inside an IF condition and 1 additional indent because your lines are inside a multi-line function call.

    PSR2 does say that multi-line function calls must be indented, but it says they must be indented once. That is documented here: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md#46-method-and-function-calls

    So the correct PSR2 code is probably this:

    public function myTestFunction()
    {
        $is_valid = true;
    
        if ($this->manual_value && !$this->_InputValidator->isValidString(
            $this->manual_value,
            1,
            2,
            Regex::STRING
        )
        ) {
            $is_valid = false;
        }
    
        return $is_valid;
    }
    

    But it doesn't look great.

    What I tend to do is combine PSR2 with some multi-line condition rules from the PEAR standard, which would give you this valid PSR2 code:

    public function myTestFunction()
    {
        $is_valid = true;
    
        if ($this->manual_value
            && !$this->_InputValidator->isValidString(
                $this->manual_value,
                1,
                2,
                Regex::STRING
            )
        ) {
            $is_valid = false;
        }
    
        return $is_valid;
    }
    

    I have no idea if PHPStorm would agree with that, but I think it might given the indent rules it appears to have.

    You can also put the && at the end of the first line instead of at the start of the second. The code I posted above is just what the PEAR coding standard uses, but PSR2 doesn't define any rules for this.