You are here

public function OpenTagNewlineSniff::process in Coder 8.2

Same name and namespace in other branches
  1. 8.3 coder_sniffer/Drupal/Sniffs/WhiteSpace/OpenTagNewlineSniff.php \Drupal\Sniffs\WhiteSpace\OpenTagNewlineSniff::process()
  2. 8.3.x coder_sniffer/Drupal/Sniffs/WhiteSpace/OpenTagNewlineSniff.php \Drupal\Sniffs\WhiteSpace\OpenTagNewlineSniff::process()

Processes this test, when one of its tokens is encountered.

Parameters

\PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where the: token was found.

int $stackPtr The position in the PHP_CodeSniffer: file's token stack where the token was found.

Return value

int End of the stack to skip the rest of the file.

File

coder_sniffer/Drupal/Sniffs/WhiteSpace/OpenTagNewlineSniff.php, line 49

Class

OpenTagNewlineSniff
Checks that there is exactly one newline after the PHP open tag.

Namespace

Drupal\Sniffs\WhiteSpace

Code

public function process(File $phpcsFile, $stackPtr) {
  $tokens = $phpcsFile
    ->getTokens();

  // Only check the very first PHP open tag in a file, ignore any others.
  if ($stackPtr !== 0) {
    return $phpcsFile->numTokens + 1;
  }
  $next = $phpcsFile
    ->findNext(T_WHITESPACE, $stackPtr + 1, null, true);

  // If there is no furhter content in this file ignore it.
  if ($next === false) {
    return $phpcsFile->numTokens + 1;
  }
  if ($tokens[$next]['line'] === 3) {
    return $phpcsFile->numTokens + 1;
  }
  $error = 'The PHP open tag must be followed by exactly one blank line';
  $fix = $phpcsFile
    ->addFixableError($error, $stackPtr, 'BlankLine');
  if ($fix === true) {
    $phpcsFile->fixer
      ->beginChangeset();
    if ($tokens[$next]['line'] === 1) {
      $phpcsFile->fixer
        ->addNewline($stackPtr);
      $phpcsFile->fixer
        ->addNewline($stackPtr);
    }
    else {
      if ($tokens[$next]['line'] === 2) {
        $phpcsFile->fixer
          ->addNewline($stackPtr);
      }
      else {
        for ($i = $stackPtr + 1; $i < $next; $i++) {
          if ($tokens[$i]['line'] > 2) {
            $phpcsFile->fixer
              ->replaceToken($i, '');
          }
        }
      }
    }
    $phpcsFile->fixer
      ->endChangeset();
  }
  return $phpcsFile->numTokens + 1;
}