You are here

protected function VariableAnalysisSniff::checkForStaticMember in Coder 8.2

Checks if the variable is a static class member.

Parameters

\PHP_CodeSniffer\Files\File $phpcsFile:

int $stackPtr:

string $varName:

string $currScope:

Return value

bool

1 call to VariableAnalysisSniff::checkForStaticMember()
VariableAnalysisSniff::processVariable in coder_sniffer/DrupalPractice/Sniffs/CodeAnalysis/VariableAnalysisSniff.php
Called to process normal member vars.

File

coder_sniffer/DrupalPractice/Sniffs/CodeAnalysis/VariableAnalysisSniff.php, line 1470

Class

VariableAnalysisSniff
Checks the for undefined function variables.

Namespace

DrupalPractice\Sniffs\CodeAnalysis

Code

protected function checkForStaticMember(File $phpcsFile, $stackPtr, $varName, $currScope) {
  $tokens = $phpcsFile
    ->getTokens();
  $token = $tokens[$stackPtr];

  // Are we a static member?
  $doubleColonPtr = $stackPtr - 1;
  if ($tokens[$doubleColonPtr]['code'] !== T_DOUBLE_COLON) {
    return false;
  }
  $classNamePtr = $stackPtr - 2;
  if ($tokens[$classNamePtr]['code'] !== T_STRING && $tokens[$classNamePtr]['code'] !== T_SELF && $tokens[$classNamePtr]['code'] !== T_STATIC) {
    return false;
  }

  // Are we referring to self:: outside a class?
  // TODO: not sure this is our business or should be some other sniff.
  if ($tokens[$classNamePtr]['code'] === T_SELF || $tokens[$classNamePtr]['code'] === T_STATIC) {
    if ($tokens[$classNamePtr]['code'] === T_SELF) {
      $err_class = 'SelfOutsideClass';
      $err_desc = 'self::';
    }
    else {
      $err_class = 'StaticOutsideClass';
      $err_desc = 'static::';
    }
    if (empty($token['conditions']) === false) {
      foreach (array_reverse($token['conditions'], true) as $scopePtr => $scopeCode) {

        // Self within a closure is invalid.
        // Note: have to fetch code from $tokens, T_CLOSURE isn't set for conditions codes.
        if ($tokens[$scopePtr]['code'] === T_CLOSURE) {
          $phpcsFile
            ->addError("Use of {$err_desc}%s inside closure.", $stackPtr, $err_class, array(
            "\${$varName}",
          ));
          return true;
        }
        if ($scopeCode === T_CLASS || $scopeCode === T_TRAIT) {
          return true;
        }
      }
    }
    $phpcsFile
      ->addError("Use of {$err_desc}%s outside class definition.", $stackPtr, $err_class, array(
      "\${$varName}",
    ));
    return true;
  }

  //end if
  return true;
}