Fix indentation of PHP code files with php-cs-fixer

You should use braces fixer to force indentation.

The body of each structure MUST be enclosed by braces. Braces should be properly placed. Body of braces should be properly indented.

indentation_type simply enforces consistency.

But since both the fixers are already included in @PSR2 so the code should be fixed correctly.

See the relevant sections in the README.


Using your code php-cs-fixer 2.6 produces the following code

<?php
$test= "abc";
    $additional_studs = "";
    if (date('m') == 12 and $term='SP') {
        $yr_suffix = date('y') + 1;
    } else {
        $yr_suffix = date('y');
    }


    function dup_stud($id, $conn)
    {//...
    }

$i = 0;

where the indentation is only partly fixed.

I reduced it to the code below

<?php
echo "a";
    echo "b";
echo "c";

It looks like a bug in php-cs-fixer.


I will answer my own question based on the findings that led me to a resolution.

While the formatting basically worked, the catch for me was the indentation. If there were some leading spaces or tabs, certain lines kept sticking out after the fix.

Since neither php-cs-fixer nor phpcbf was able to fix the indentation properly I took desperate measures and trimmed every leading whitespace from each line as preparatory step with sed in a script like this:

sed "s/^[ \t]*//" -i test.php

Then I processed some prepped files again with php-cs-fixer and phpcbf to find out which one does a better job formatting the files according to PSR-2. It's shameful, but both fixers failed again - now showing some different shortcomings (i.e. bugs). To cut a long story short, I finally learnt that coupling the two tools leads to properly formatted code files. What a mess.

So, after sed, I run phpcbf

phpcbf --standard="PSR2" test.php

followed by

php-cs-fixer fix test.php --rules=@PSR2

And all the sudden I have beautifully PSR-2 formatted PHP files. Not the most efficient way, but it does the job.

Some additional comments:

  • If you would like to apply additional fixer rules, I would suggest to do this in a 4th step using a different, more complete php_cs configuration from a PSR-2 baseline formatting (because, you know, there are more fixer issues..).
  • I suggest to use 4 spaces as indent, as required by PSR-2. According to my experience things get even more complicated if you insist to have tabs.
  • The described procedure wouldn't be necessary if php-cs-fixer and phpcbf would not have so many issues. I will report them one after another, and hopefully, in the future the same can be achieved in one go.