You are here

protected function FunctionCommentSniff::isAliasedType in Coder 8.2

Same name and namespace in other branches
  1. 8.3 coder_sniffer/Drupal/Sniffs/Commenting/FunctionCommentSniff.php \Drupal\Sniffs\Commenting\FunctionCommentSniff::isAliasedType()
  2. 8.3.x coder_sniffer/Drupal/Sniffs/Commenting/FunctionCommentSniff.php \Drupal\Sniffs\Commenting\FunctionCommentSniff::isAliasedType()

Checks if a used type hint is an alias defined by a "use" statement.

Parameters

string $typeHint The type hint used.:

string $suggestedTypeHint The fully qualified type to: check against.

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

Return value

boolean

1 call to FunctionCommentSniff::isAliasedType()
FunctionCommentSniff::processParams in coder_sniffer/Drupal/Sniffs/Commenting/FunctionCommentSniff.php
Process the function parameter comments.

File

coder_sniffer/Drupal/Sniffs/Commenting/FunctionCommentSniff.php, line 955

Class

FunctionCommentSniff
Parses and verifies the doc comments for functions. Largely copied from PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\FunctionCommentSniff.

Namespace

Drupal\Sniffs\Commenting

Code

protected function isAliasedType($typeHint, $suggestedTypeHint, File $phpcsFile) {
  $tokens = $phpcsFile
    ->getTokens();

  // Iterate over all "use" statements in the file.
  $usePtr = 0;
  while ($usePtr !== false) {
    $usePtr = $phpcsFile
      ->findNext(T_USE, $usePtr + 1);
    if ($usePtr === false) {
      return false;
    }

    // Only check use statements in the global scope.
    if (empty($tokens[$usePtr]['conditions']) === false) {
      continue;
    }

    // Now comes the original class name, possibly with namespace
    // backslashes.
    $originalClass = $phpcsFile
      ->findNext(Tokens::$emptyTokens, $usePtr + 1, null, true);
    if ($originalClass === false || $tokens[$originalClass]['code'] !== T_STRING && $tokens[$originalClass]['code'] !== T_NS_SEPARATOR) {
      continue;
    }
    $originalClassName = '';
    while (in_array($tokens[$originalClass]['code'], array(
      T_STRING,
      T_NS_SEPARATOR,
    )) === true) {
      $originalClassName .= $tokens[$originalClass]['content'];
      $originalClass++;
    }
    if (ltrim($originalClassName, '\\') !== ltrim($suggestedTypeHint, '\\')) {
      continue;
    }

    // Now comes the "as" keyword signaling an alias name for the class.
    $asPtr = $phpcsFile
      ->findNext(Tokens::$emptyTokens, $originalClass + 1, null, true);
    if ($asPtr === false || $tokens[$asPtr]['code'] !== T_AS) {
      continue;
    }

    // Now comes the name the class is aliased to.
    $aliasPtr = $phpcsFile
      ->findNext(Tokens::$emptyTokens, $asPtr + 1, null, true);
    if ($aliasPtr === false || $tokens[$aliasPtr]['code'] !== T_STRING || $tokens[$aliasPtr]['content'] !== $typeHint) {
      continue;
    }

    // We found a use statement that aliases the used type hint!
    return true;
  }

  //end while
  return false;
}