You are here

public function GlobalDrupalSniff::process in Coder 8.2

Same name and namespace in other branches
  1. 8.3 coder_sniffer/DrupalPractice/Sniffs/Objects/GlobalDrupalSniff.php \DrupalPractice\Sniffs\Objects\GlobalDrupalSniff::process()
  2. 8.3.x coder_sniffer/DrupalPractice/Sniffs/Objects/GlobalDrupalSniff.php \DrupalPractice\Sniffs\Objects\GlobalDrupalSniff::process()

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

Parameters

\PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.:

int $stackPtr The position of the current token: in the stack passed in $tokens.

Return value

void

File

coder_sniffer/DrupalPractice/Sniffs/Objects/GlobalDrupalSniff.php, line 68

Class

GlobalDrupalSniff
Checks that \Drupal::service() and friends is not used in forms, controllers, services.

Namespace

DrupalPractice\Sniffs\Objects

Code

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

  // We are only interested in Drupal:: static method calls, not in the global
  // scope.
  if ($tokens[$stackPtr]['content'] !== 'Drupal' || $tokens[$stackPtr + 1]['code'] !== T_DOUBLE_COLON || isset($tokens[$stackPtr + 2]) === false || $tokens[$stackPtr + 2]['code'] !== T_STRING || isset($tokens[$stackPtr + 3]) === false || $tokens[$stackPtr + 3]['code'] !== T_OPEN_PARENTHESIS || empty($tokens[$stackPtr]['conditions']) === true) {
    return;
  }

  // Check that this statement is not in a static function.
  foreach ($tokens[$stackPtr]['conditions'] as $conditionPtr => $conditionCode) {
    if ($conditionCode === T_FUNCTION && $phpcsFile
      ->getMethodProperties($conditionPtr)['is_static'] === true) {
      return;
    }
  }

  // Check if the class extends another class and get the name of the class
  // that is extended.
  $classPtr = key($tokens[$stackPtr]['conditions']);
  $extendsName = $phpcsFile
    ->findExtendedClassName($classPtr);
  if (($extendsName === false || in_array($extendsName, static::$baseClasses) === false) && Project::isServiceClass($phpcsFile, $classPtr) === false) {
    return;
  }
  $warning = '\\Drupal calls should be avoided in classes, use dependency injection instead';
  $phpcsFile
    ->addWarning($warning, $stackPtr, 'GlobalDrupal');
}