Search code examples
phpphpcodesniffer

Sniffer Snippet to allow brackets on new line


Is there a codesniffer snippet which allows/forces { } to be put on newlines for every function/method?

Basically, forcing something like this:

if (TRUE)
{
     // Code logic
}
else
{
    // Code Logic
}

And

public function test()
{
     // Code logic
}

Solution

  • Yes, there is a ready one. It's called OpeningFunctionBraceBsdAllmanSniff and you can find it under /path/to/CodeSniffer/Standards/Generic/Sniffs/Functions. But that's only for functions' declarations.

    For control structures you can take the /path/to/Standards/Squiz/Sniffs/ControlStructures/ControlSignatureSniff.php and tweak the pattern array from

    protected function getPatterns()
    {
        return array(
                'try {EOL...} catch (...) {EOL',
                'do {EOL...} while (...);EOL',
                'while (...) {EOL',
                'for (...) {EOL',
                'if (...) {EOL',
                'foreach (...) {EOL',
                '} else if (...) {EOL',
                '} elseif (...) {EOL',
                '} else {EOL',
               );
    
    }//end getPatterns()
    

    to, i.e.

    protected function getPatterns()
    {
        return array(
                'try {EOL...} catch (...) {EOL',
                'do {EOL...} while (...);EOL',
                'while (...) {EOL',
                'for (...) {EOL',
                'if (...)EOL{',              // that's what you need
                'foreach (...) {EOL',
                '} else if (...) {EOL',
                '} elseif (...) {EOL',
                '} elseEOL{',               // and this
               );
    
    }//end getPatterns()
    

    If you need to apply the same rule to other control structure, you can go the same way, by changing the patterns in the array.

    Update: one cleaner solution would be, of course, to write your own class which extends the above and overrides the the getPatterns() method.