6

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
}
ThomasVdBerge
  • 7,483
  • 4
  • 44
  • 62
  • Have they to exist in constructs like `if (true) do1(); else do2();` or shall they only put into newlines if they exist? – bwoebi Apr 20 '13 at 09:05
  • I already have another snippet in place which forces the body to be always put between brackets. So yep, they have to exist – ThomasVdBerge Apr 20 '13 at 09:16

1 Answers1

7

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.

Havelock
  • 6,913
  • 4
  • 34
  • 42
  • This does not seem to work if the bracket is indented `Expected "if (...)\n{"; found "if (...)\n\t\t{"` – Mikulas Dite Aug 18 '13 at 11:20
  • @MikulasDite you may want to convert your tabs into spaces. If you, for some reason don't want to do this in your editor/IDE, PHPCS can do it for you. You need to set the the corresponding option, i.e. your tabs are 4 spaces: `$ phpcs --config-set tab_width 4`, as it's [described in the documentation](http://pear.php.net/manual/en/package.php.php-codesniffer.config-options.php) – Havelock Sep 05 '13 at 09:42
  • 1
    This solved the tab problem for me: `'if (...)EOL...{'` (edited Havelock's solutions) – ippi Dec 16 '13 at 02:33