function TestClassClassMetadata::processNode

File

core/tests/PHPStan/Rules/TestClassClassMetadata.php, line 78

Class

TestClassClassMetadata
Rules class-level PHPUnit test metadata in test classes.

Namespace

Drupal\PHPStan\Rules

Code

public function processNode(Node $node, Scope $scope) : array {
  $class = $node->getClassReflection();
  // We only process PHPUnit test classes here.
  if (!$class->isSubclassOfClass($this->reflectionProvider
    ->getClass(TestCase::class))) {
    return [];
  }
  $fails = [];
  if ($class->isAbstract()) {
    // Abstract test classes (i.e. base test classes) should not have any
    // metadata on the class definition, neither attributes nor annotations.
    foreach ($class->getAttributes() as $attribute) {
      if (str_starts_with($attribute->getName(), 'PHPUnit\\Framework\\Attributes\\')) {
        $fails[] = RuleErrorBuilder::message("Abstract test class {$class->getName()} must not add attribute {$attribute->getName()}.")
          ->identifier('abstractTestClass.metadataForbidden')
          ->line($node->getStartLine())
          ->build();
      }
    }
    $resolvedPhpDoc = $class->getResolvedPhpDoc();
    if ($resolvedPhpDoc) {
      foreach ($resolvedPhpDoc->getPhpDocNodes() as $phpDocNode) {
        foreach ($phpDocNode->getTags() as $tag) {
          if (in_array($tag->name, $this->annotationTargets, TRUE)) {
            $fails[] = RuleErrorBuilder::message("Abstract test class {$class->getName()} must not add annotation {$tag->name}.")
              ->identifier('abstractTestClass.metadataForbidden')
              ->line($node->getStartLine())
              ->build();
          }
        }
      }
    }
  }
  else {
    // Concrete test classes should no longer have PHPUnit metadata
    // annotations.
    $resolvedPhpDoc = $class->getResolvedPhpDoc();
    if ($resolvedPhpDoc) {
      foreach ($resolvedPhpDoc->getPhpDocNodes() as $phpDocNode) {
        foreach ($phpDocNode->getTags() as $tag) {
          if (in_array($tag->name, $this->annotationTargets, TRUE)) {
            $fails[] = RuleErrorBuilder::message("Test class {$class->getName()} must not add annotation {$tag->name}.")
              ->identifier('testClass.metadataForbidden')
              ->line($node->getStartLine())
              ->build();
          }
        }
      }
    }
  }
  return $fails;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.