You are here

public function SectionStorageManagerTest::testFindByContextCacheableSectionStorage in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/layout_builder/tests/src/Unit/SectionStorageManagerTest.php \Drupal\Tests\layout_builder\Unit\SectionStorageManagerTest::testFindByContextCacheableSectionStorage()

@covers ::findByContext

File

core/modules/layout_builder/tests/src/Unit/SectionStorageManagerTest.php, line 265

Class

SectionStorageManagerTest
@coversDefaultClass \Drupal\layout_builder\SectionStorage\SectionStorageManager

Namespace

Drupal\Tests\layout_builder\Unit

Code

public function testFindByContextCacheableSectionStorage() {
  $cacheability = new CacheableMetadata();
  $contexts = [
    'foo' => new Context(new ContextDefinition('foo')),
  ];
  $definitions = [
    'first' => new SectionStorageDefinition(),
    'second' => new SectionStorageDefinition(),
  ];
  $this->discovery
    ->getDefinitions()
    ->willReturn($definitions);

  // Create a plugin that has cacheability info itself as a cacheable object
  // and from within ::isApplicable() but is not applicable.
  $first_plugin = $this
    ->prophesize(SectionStorageInterface::class);
  $first_plugin
    ->willImplement(CacheableDependencyInterface::class);
  $first_plugin
    ->getCacheContexts()
    ->shouldNotBeCalled();
  $first_plugin
    ->getCacheTags()
    ->shouldNotBeCalled();
  $first_plugin
    ->getCacheMaxAge()
    ->shouldNotBeCalled();
  $first_plugin
    ->isApplicable($cacheability)
    ->will(function ($arguments) {
    $arguments[0]
      ->addCacheTags([
      'first_plugin',
    ]);
    return FALSE;
  });

  // Create a plugin that adds cacheability info from within ::isApplicable()
  // and is applicable.
  $second_plugin = $this
    ->prophesize(SectionStorageInterface::class);
  $second_plugin
    ->isApplicable($cacheability)
    ->will(function ($arguments) {
    $arguments[0]
      ->addCacheTags([
      'second_plugin',
    ]);
    return TRUE;
  });
  $this->factory
    ->createInstance('first', [])
    ->willReturn($first_plugin
    ->reveal());
  $this->factory
    ->createInstance('second', [])
    ->willReturn($second_plugin
    ->reveal());

  // Do not do any filtering based on context.
  $this->contextHandler
    ->filterPluginDefinitionsByContexts($contexts, $definitions)
    ->willReturnArgument(1);
  $this->contextHandler
    ->applyContextMapping($first_plugin, $contexts)
    ->shouldBeCalled();
  $this->contextHandler
    ->applyContextMapping($second_plugin, $contexts)
    ->shouldBeCalled();
  $result = $this->manager
    ->findByContext($contexts, $cacheability);
  $this
    ->assertSame($second_plugin
    ->reveal(), $result);
  $this
    ->assertSame([
    'first_plugin',
    'second_plugin',
  ], $cacheability
    ->getCacheTags());
}