function AttributeClassDiscoveryCachedTest::testGetDefinitions

Same name and namespace in other branches
  1. 11.x core/tests/Drupal/Tests/Component/Plugin/Attribute/AttributeClassDiscoveryCachedTest.php \Drupal\Tests\Component\Plugin\Attribute\AttributeClassDiscoveryCachedTest::testGetDefinitions()

Tests that getDefinitions() retrieves the file cache correctly.

@covers ::getDefinitions

File

core/tests/Drupal/Tests/Component/Plugin/Attribute/AttributeClassDiscoveryCachedTest.php, line 44

Class

AttributeClassDiscoveryCachedTest
@coversDefaultClass \Drupal\Component\Plugin\Discovery\AttributeClassDiscovery[[api-linebreak]] @group Attribute @runTestsInSeparateProcesses

Namespace

Drupal\Tests\Component\Plugin\Attribute

Code

public function testGetDefinitions() : void {
  // Path to the classes which we'll discover and parse annotation.
  $discovery_path = __DIR__ . "/../../../../../fixtures/plugins/Plugin";
  // File path that should be discovered within that directory.
  $file_path = $discovery_path . '/PluginNamespace/AttributeDiscoveryTest1.php';
  // Define a file path within the directory that should not be discovered.
  $non_discoverable_file_path = $discovery_path . '/PluginNamespace/AttributeDiscoveryTest2.php';
  $discovery = new AttributeClassDiscovery([
    'com\\example' => [
      $discovery_path,
    ],
  ]);
  $this->assertEquals([
    'discovery_test_1' => [
      'id' => 'discovery_test_1',
      'class' => 'com\\example\\PluginNamespace\\AttributeDiscoveryTest1',
    ],
  ], $discovery->getDefinitions());
  // Gain access to the file cache.
  $ref_file_cache = new \ReflectionProperty($discovery, 'fileCache');
  $ref_file_cache->setAccessible(TRUE);
  /** @var \Drupal\Component\FileCache\FileCacheInterface $file_cache */
  $file_cache = $ref_file_cache->getValue($discovery);
  // The valid plugin definition should be cached.
  $this->assertEquals([
    'id' => 'discovery_test_1',
    'class' => 'com\\example\\PluginNamespace\\AttributeDiscoveryTest1',
  ], unserialize($file_cache->get($file_path)['content']));
  // The plugin that extends a missing class should not be cached.
  $this->assertNull($file_cache->get($non_discoverable_file_path));
  // Change the file cache entry.
  // The file cache is keyed by the file path, and we'll add some known
  // content to test against.
  $file_cache->set($file_path, [
    'id' => 'wrong_id',
    'content' => serialize([
      'an' => 'array',
    ]),
  ]);
  // Now perform the same query and check for the cached results.
  $this->assertEquals([
    'wrong_id' => [
      'an' => 'array',
    ],
  ], $discovery->getDefinitions());
}

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