ContextDefinition example

/** * Selects the page display variant. * * @param \Drupal\Core\Render\PageDisplayVariantSelectionEvent $event * The event to process. */
  public function onSelectPageDisplayVariant(PageDisplayVariantSelectionEvent $event) {
    $event->setPluginId('display_variant_test');
    $event->setPluginConfiguration(['required_configuration' => 'A very important, required value.']);
    $event->addCacheTags(['custom_cache_tag']);

    $context = new Context(new ContextDefinition('string', NULL, TRUE), 'Explicitly passed in context.');
    $event->setContexts(['context' => $context]);
  }

  /** * {@inheritdoc} */
  public static function getSubscribedEvents(): array {
    $events[RenderEvents::SELECT_PAGE_DISPLAY_VARIANT][] = ['onSelectPageDisplayVariant'];
    return $events;
  }

}

  protected function setUp(): void {
    parent::setUp();

    entity_test_create_bundle('bundle_with_extra_fields');
    $this->installEntitySchema('entity_test');
    $this->installEntitySchema('user');
    $this->installConfig(['layout_builder_defaults_test']);

    $definition = (new SectionStorageDefinition())
      ->addContextDefinition('display', EntityContextDefinition::fromEntityTypeId('entity_view_display'))
      ->addContextDefinition('view_mode', new ContextDefinition('string'));
    $this->plugin = DefaultsSectionStorage::create($this->container, [], 'defaults', $definition);
  }

  /** * Tests installing defaults via config install. */
  public function testConfigInstall() {
    /** @var \Drupal\layout_builder\Entity\LayoutEntityDisplayInterface $display */
    $display = LayoutBuilderEntityViewDisplay::load('entity_test.bundle_with_extra_fields.default');
    $section = $display->getSection(0);
    $this->assertInstanceOf(Section::class$section);
    

class ContextTypedDataTest extends KernelTestBase {

  /** * Tests that contexts can be serialized. */
  public function testSerialize() {
    $definition = new ContextDefinition('any');
    $data_definition = DataDefinition::create('string');
    $typed_data = new StringData($data_definition);
    $typed_data->setValue('example string');
    $context = new Context($definition$typed_data);
    // getContextValue() will cause the context to reference the typed data     // manager service.     $value = $context->getContextValue();
    $context = serialize($context);
    $context = unserialize($context);
    $this->assertSame($value$context->getContextValue());
  }

  
if ($unqualified_context_ids) {
      foreach ($unqualified_context_ids as $unqualified_context_id) {
        if (array_search($unqualified_context_id$language_types) === FALSE) {
          unset($language_types[$unqualified_context_id]);
        }
      }
    }

    $result = [];
    foreach ($language_types as $type_key) {
      if (isset($info[$type_key]['name'])) {
        $context = new Context(new ContextDefinition('language', $info[$type_key]['name'])$this->languageManager->getCurrentLanguage($type_key));

        $cacheability = new CacheableMetadata();
        $cacheability->setCacheContexts(['languages:' . $type_key]);
        $context->addCacheableDependency($cacheability);

        $result[$type_key] = $context;
      }
    }

    return $result;
  }

  
/** * {@inheritdoc} */
  public function getContextDefinition() {
    if ($context_definition = parent::getContextDefinition()) {
      return $context_definition;
    }

    // If the parent does not provide a context definition through the     // validation plugin, fall back to the integer type.     return new ContextDefinition('integer', $this->adminLabel(), FALSE);
  }

}


  /** * Provides test data for ::testIsSatisfiedBy(). */
  public function providerTestIsSatisfiedBy() {
    $data = [];

    // Simple data types.     $data['both any'] = [
      TRUE,
      new ContextDefinition('any'),
      new ContextDefinition('any'),
    ];
    $data['requirement any'] = [
      TRUE,
      new ContextDefinition('any'),
      new ContextDefinition('integer'),
    ];
    $data['integer, out of range'] = [
      FALSE,
      (new ContextDefinition('integer'))->addConstraint('Range', ['min' => 0, 'max' => 10]),
      new ContextDefinition('integer'),
      
return $data;
  }

  /** * Tests the convert() method with an invalid entity type. */
  public function testConvertWithInvalidEntityType() {
    $this->setUpMocks();

    $contexts = [
      EntityRepositoryInterface::CONTEXT_ID_LEGACY_CONTEXT_OPERATION => new Context(new ContextDefinition('string'), 'entity_upcast'),
    ];

    $plugin_id = 'invalid_id';
    $this->entityRepository->expects($this->once())
      ->method('getCanonical')
      ->with($plugin_id, 'id', $contexts)
      ->willThrowException(new PluginNotFoundException($plugin_id));

    $this->expectException(PluginNotFoundException::class);

    $this->entityConverter->convert('id', ['type' => 'entity:' . $plugin_id], 'foo', ['foo' => 'id']);
  }
/** * @covers ::findByContext * * @dataProvider providerTestFindByContext * * @param bool $plugin_is_applicable * The result for the plugin's isApplicable() method to return. */
  public function testFindByContext($plugin_is_applicable) {
    $cacheability = new CacheableMetadata();
    $contexts = [
      'foo' => new Context(new ContextDefinition('foo')),
    ];
    $definitions = [
      'no_access' => (new SectionStorageDefinition())->setClass(SectionStorageInterface::class),
      'missing_contexts' => (new SectionStorageDefinition())->setClass(SectionStorageInterface::class),
      'provider_access' => (new SectionStorageDefinition())->setClass(SectionStorageInterface::class),
    ];
    $this->discovery->getDefinitions()->willReturn($definitions);

    $provider_access = $this->prophesize(SectionStorageInterface::class);
    $provider_access->isApplicable($cacheability)->willReturn($plugin_is_applicable);

    
TRUE,
      EntityContextDefinition::fromEntityType($content),
      EntityContextDefinition::fromEntityType($content)->addConstraint('EntityType', 'test_config'),
    ];
    $data['config entity, matching type, no value'] = [
      TRUE,
      EntityContextDefinition::fromEntityType($config),
      EntityContextDefinition::fromEntityType($config),
    ];
    $data['generic entity requirement, specific context'] = [
      TRUE,
      new ContextDefinition('entity'),
      EntityContextDefinition::fromEntityType($config),
    ];
    $data['specific requirement, generic entity context'] = [
      FALSE,
      EntityContextDefinition::fromEntityType($content),
      new ContextDefinition('entity'),
    ];

    return $data;
  }

  
$entity_prophecy->getCacheTags()->willReturn([]);
    $entity_prophecy->getCacheMaxAge()->willReturn(0);

    $plugin_definition += [
      'provider' => 'test',
      'default_formatter' => '',
      'category' => 'Test',
      'admin_label' => 'Test Block',
      'bundles' => ['entity_test'],
      'context_definitions' => [
        'entity' => EntityContextDefinition::fromEntityTypeId('entity_test')->setLabel('Test'),
        'view_mode' => new ContextDefinition('string'),
      ],
    ];
    $formatter_manager = $this->prophesize(FormatterPluginManager::class);
    $module_handler = $this->prophesize(ModuleHandlerInterface::class);

    $block = new FieldBlock(
      $configuration,
      'field_block:entity_test:entity_test:the_field_name',
      $plugin_definition,
      $this->entityFieldManager->reveal(),
      $formatter_manager->reveal(),
      
public function deriveContextsFromRoute($value$definition$name, array $defaults) {
    $contexts = [];

    if ($entity = $this->extractEntityFromRoute($value$defaults)) {
      $contexts['entity'] = EntityContext::fromEntity($entity);
      // @todo Expand to work for all view modes in       // https://www.drupal.org/node/2907413.       $view_mode = 'full';
      // Retrieve the actual view mode from the returned view display as the       // requested view mode may not exist and a fallback will be used.       $view_mode = LayoutBuilderEntityViewDisplay::collectRenderDisplay($entity$view_mode)->getMode();
      $contexts['view_mode'] = new Context(new ContextDefinition('string')$view_mode);
    }
    return $contexts;
  }

  /** * Extracts an entity from the route values. * * @param mixed $value * The raw value from the route. * @param array $defaults * The route defaults array. * * @return \Drupal\Core\Entity\EntityInterface|null * The entity for the route, or NULL if none exist. * * @see \Drupal\layout_builder\SectionStorageInterface::deriveContextsFromRoute() * @see \Drupal\Core\ParamConverter\ParamConverterInterface::convert() */
public function testInvalidContextId() {
    $lazy_context_repository = new LazyContextRepository($this->container, ['test_provider']);
    $this->expectException(\AssertionError::class);
    $this->expectExceptionMessage('You must provide the context IDs in the @{service_id}:{unqualified_context_id} format.');
    $lazy_context_repository->getRuntimeContexts(['test_context', '@test_provider:test_context1']);
  }

  /** * @covers ::getRuntimeContexts */
  public function testGetRuntimeStaticCache() {
    $context0 = new Context(new ContextDefinition('example'));
    $context1 = new Context(new ContextDefinition('example'));

    $context_provider = $this->prophesize('\Drupal\Core\Plugin\Context\ContextProviderInterface');
    $context_provider->getRuntimeContexts(['test_context0', 'test_context1'])
      ->shouldBeCalledTimes(1)
      ->willReturn(['test_context0' => $context0, 'test_context1' => $context1]);
    $context_provider = $context_provider->reveal();
    $this->container->set('test_provider', $context_provider);

    $lazy_context_repository = new LazyContextRepository($this->container, ['test_provider']);
    $lazy_context_repository->getRuntimeContexts(['@test_provider:test_context0', '@test_provider:test_context1']);
    

    $display
      ->setOverridable()
      ->save();

    $entity = EntityTest::create([OverridesSectionStorage::FIELD_NAME => $section_data]);
    $entity->save();

    $account = $this->setUpCurrentUser([]$permissions);

    $this->plugin->setContext('entity', EntityContext::fromEntity($entity));
    $this->plugin->setContext('view_mode', new Context(new ContextDefinition('string'), 'default'));

    // Check access with both the global current user as well as passing one in.     $result = $this->plugin->access('view');
    $this->assertSame($expected$result);
    $result = $this->plugin->access('view', $account);
    $this->assertSame($expected$result);

    // Create a translation.     ConfigurableLanguage::createFromLangcode('es')->save();
    $entity = EntityTest::load($entity->id());
    $translation = $entity->addTranslation('es');
    

  protected function getSectionList(array $section_data) {
    $config = $this->container->get('config.factory')->getEditable('layout_builder_test.test_simple_config.foobar');
    $section_data = array_map(function DSection $section) {
      return $section->toArray();
    }$section_data);
    $config->set('sections', $section_data)->save();

    $definition = new SectionStorageDefinition(['id' => 'test_simple_config']);
    $plugin = SimpleConfigSectionStorage::create($this->container, [], 'test_simple_config', $definition);
    $plugin->setContext('config_id', new Context(new ContextDefinition('string'), 'foobar'));
    return $plugin;
  }

}

  public function testCheckRequirements($contexts$requirements$expected) {
    $this->assertSame($expected$this->contextHandler->checkRequirements($contexts$requirements));
  }

  /** * Provides data for testCheckRequirements(). */
  public function providerTestCheckRequirements() {
    $requirement_optional = new ContextDefinition();
    $requirement_optional->setRequired(FALSE);

    $requirement_any = new ContextDefinition();
    $requirement_any->setRequired(TRUE);

    $context_any = $this->createMock('Drupal\Core\Plugin\Context\ContextInterface');
    $context_any->expects($this->atLeastOnce())
      ->method('getContextDefinition')
      ->willReturn(new ContextDefinition('any'));

    $requirement_specific = new ContextDefinition('string');
    
Home | Imprint | This part of the site doesn't use cookies.