MultipleEmptyLinesSniff.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Sniffs\Whitespace;
  7. use PHP_CodeSniffer\Sniffs\Sniff;
  8. use PHP_CodeSniffer\Files\File;
  9. /**
  10. * Class MultipleEmptyLinesSniff
  11. */
  12. class MultipleEmptyLinesSniff implements Sniff
  13. {
  14. /**
  15. * @inheritdoc
  16. */
  17. public function register()
  18. {
  19. return [T_WHITESPACE];
  20. }
  21. /**
  22. * @inheritdoc
  23. */
  24. public function process(File $phpcsFile, $stackPtr)
  25. {
  26. $tokens = $phpcsFile->getTokens();
  27. if ($phpcsFile->hasCondition($stackPtr, T_FUNCTION)
  28. || $phpcsFile->hasCondition($stackPtr, T_CLASS)
  29. || $phpcsFile->hasCondition($stackPtr, T_INTERFACE)
  30. ) {
  31. if ($tokens[($stackPtr - 1)]['line'] < $tokens[$stackPtr]['line']
  32. && $tokens[($stackPtr - 2)]['line'] === $tokens[($stackPtr - 1)]['line']
  33. ) {
  34. // This is an empty line and the line before this one is not
  35. // empty, so this could be the start of a multiple empty line block
  36. $next = $phpcsFile->findNext(T_WHITESPACE, $stackPtr, null, true);
  37. $lines = $tokens[$next]['line'] - $tokens[$stackPtr]['line'];
  38. if ($lines > 1) {
  39. $error = 'Code must not contain multiple empty lines in a row; found %s empty lines';
  40. $data = [$lines];
  41. $phpcsFile->addError($error, $stackPtr, 'MultipleEmptyLines', $data);
  42. }
  43. }
  44. }
  45. }
  46. }