function ImplementationNameTest::testImplementationNames

Tests source contents and filenames against the reviewed allowlist.

File

core/themes/default_admin/tests/src/Unit/ImplementationNameTest.php, line 134

Class

ImplementationNameTest
Tests that inherited implementation names have an explicit rationale.

Namespace

Drupal\Tests\default_admin\Unit

Code

public function testImplementationNames() : void {
  $theme_path = dirname(__DIR__, 3);
  $allowlist_path = $theme_path . '/tests/fixtures/implementation-name-allowlist.json';
  $allowlist = json_decode(file_get_contents($allowlist_path), TRUE, flags: JSON_THROW_ON_ERROR);
  $matched_allowlist_entries = [];
  $unexpected = [];
  $name_pattern = '/(?:\\b(?:gin|Gin|claro|Claro)\\b' . '|(?<![A-Za-z])(?:gin|claro)(?=[._-]|[A-Z])' . '|(?<![A-Za-z])(?:Gin|Claro)(?=[A-Z]))/';
  $extensions = [
    'css',
    'js',
    'json',
    'md',
    'php',
    'svg',
    'twig',
    'yml',
  ];
  $directory = new \RecursiveDirectoryIterator($theme_path, \FilesystemIterator::SKIP_DOTS);
  $files = new \RecursiveIteratorIterator($directory);
  $excluded = [
    'tests/fixtures/implementation-name-allowlist.json',
  ];
  foreach ($files as $file) {
    if (!$file->isFile()) {
      continue;
    }
    $relative_path = substr($file->getPathname(), strlen($theme_path) + 1);
    if (in_array($relative_path, $excluded, TRUE)) {
      continue;
    }
    if (preg_match('/(?:gin|claro)/i', $file->getFilename())) {
      $unexpected[] = $relative_path . ': inherited name in filename';
    }
    if (!in_array($file->getExtension(), $extensions, TRUE)) {
      continue;
    }
    foreach (file($file->getPathname()) as $line_number => $line) {
      if (!preg_match($name_pattern, $line)) {
        continue;
      }
      $allowed = FALSE;
      foreach ($allowlist as $index => $entry) {
        if ($entry['path'] === $relative_path && str_contains($line, $entry['pattern'])) {
          $matched_allowlist_entries[$index] = TRUE;
          $allowed = TRUE;
          break;

        }
      }
      if (!$allowed) {
        $unexpected[] = sprintf('%s:%d: %s', $relative_path, $line_number + 1, trim($line));
      }
    }
  }
  foreach ($allowlist as $index => $entry) {
    if (empty($matched_allowlist_entries[$index])) {
      $unexpected[] = sprintf('Unused allowlist entry: %s: %s (%s)', $entry['path'], $entry['pattern'], $entry['reason']);
    }
  }
  self::assertSame([], $unexpected, implode("\n", $unexpected));
}

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