Skip to content
Snippets Groups Projects
Commit c2abe6f4 authored by christian.wiedemann's avatar christian.wiedemann
Browse files

Issue #3467502 by christian.wiedemann, just_like_good_vibes, b.khouy: Replace...

Issue #3467502 by christian.wiedemann, just_like_good_vibes, b.khouy: Replace ContextHelper with Context
parent a260ae96
Branches
Tags
1 merge request!183Add context entity resolver service with layout builder and field layout resolver
Pipeline #279327 passed with warnings
Showing
with 548 additions and 114 deletions
......@@ -14,8 +14,8 @@ use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextDefinition;
use Drupal\Core\Plugin\Context\EntityContext;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\ui_patterns\ContextHelperInterface;
use Drupal\ui_patterns\Form\ComponentFormBuilderTrait;
use Drupal\ui_patterns\Resolver\ChainContextEntityResolverInterface;
use Drupal\ui_patterns\SourcePluginBase;
use Drupal\ui_patterns_blocks\Plugin\Derivative\ComponentBlock as DerivativeComponentBlock;
use Symfony\Component\DependencyInjection\ContainerInterface;
......@@ -42,14 +42,14 @@ class ComponentBlock extends BlockBase implements ContainerFactoryPluginInterfac
* The plugin ID for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\ui_patterns\ContextHelperInterface $contextHelper
* The context helper service.
* @param \Drupal\ui_patterns\Resolver\ChainContextEntityResolver $chainContextEntityResolver
* The chained context entity resolver.
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
protected ContextHelperInterface $contextHelper,
protected ChainContextEntityResolverInterface $chainContextEntityResolver,
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
......@@ -62,7 +62,7 @@ class ComponentBlock extends BlockBase implements ContainerFactoryPluginInterfac
$configuration,
$plugin_id,
$plugin_definition,
$container->get('ui_patterns.context_helper'),
$container->get('ui_patterns.chain_context_entity_resolver'),
);
}
......@@ -128,14 +128,16 @@ class ComponentBlock extends BlockBase implements ContainerFactoryPluginInterfac
* Source contexts.
*/
protected function getComponentSourceContexts(FormStateInterface $form_state = NULL): array {
$gatheredContexts = $form_state ? $form_state->getTemporaryValue('gathered_contexts') : [];
$this->contextHelper->applyContextMapping($this, $gatheredContexts ?: []);
if (!isset($this->context['entity']) || !($this->context['entity']->getContextValue() instanceof EntityInterface)) {
if ($entity = $this->contextHelper->guessEntity($this->context, $form_state)) {
$contexts = $this->context;
if ($form_state !== NULL) {
$contexts['ui_patterns:form_state'] = new Context(ContextDefinition::create('any'), $form_state);
}
if ($entity = $this->chainContextEntityResolver->guessEntity($contexts)) {
$this->context['entity'] = EntityContext::fromEntity($entity);
}
}
if (!$this->context["bundle"] && isset($this->context["entity"])) {
if (!isset($this->context["bundle"]) && isset($this->context["entity"])) {
$this->context['bundle'] = new Context(ContextDefinition::create('string'), $this->context["entity"]->getContextValue()->bundle() ?? "");
}
return $this->context;
......
......@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Drupal\ui_patterns_field_formatters\Plugin\Field\FieldFormatter;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
......@@ -30,11 +31,32 @@ abstract class ComponentFormatterBase extends FormatterBase {
protected $componentPluginManager;
/**
* The context helper.
* The entity type manager.
*
* @var \Drupal\ui_patterns\ContextHelperInterface
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $contextHelper;
protected $entityTypeManager;
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* The sample entity generator.
*
* @var \Drupal\ui_patterns\Entity\SampleEntityGenerator
*/
protected $sampleEntityGenerator;
/**
* The chain context entity resolver.
*
* @var \Drupal\ui_patterns\Resolver\ContextEntityResolverInterface
*/
protected $chainContextEntityResolver;
/**
* The provided plugin contexts.
......@@ -63,7 +85,12 @@ abstract class ComponentFormatterBase extends FormatterBase {
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$instance->componentPluginManager = $container->get('plugin.manager.sdc');
$instance->contextHelper = $container->get('ui_patterns.context_helper');
$instance->entityTypeManager = $container->get('entity_type.manager');
$instance->entityFieldManager = $container->get('entity_field.manager');
$instance->sampleEntityGenerator = $container->get('ui_patterns.sample_entity_generator');
$instance->chainContextEntityResolver = $container->get('ui_patterns.chain_context_entity_resolver');
return $instance;
}
......@@ -136,6 +163,46 @@ abstract class ComponentFormatterBase extends FormatterBase {
];
}
/**
* {@inheritdoc}
*/
protected function checkEntityHasField(EntityInterface $entity, string $entity_type_id, string $field_name) : bool {
$field_definitions = $this->entityFieldManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle());
return ($entity->getEntityTypeId() === $entity_type_id &&
array_key_exists($field_name, $field_definitions));
}
/**
* Find an entity bundle which has a field.
*
* @param string $entity_type_id
* The entity type id.
* @param string $field_name
* The field name to be found in searched bundle.
*
* @return string
* The bundle.
*/
protected function findEntityBundleWithField(string $entity_type_id, string $field_name) : string {
// @todo better implementation with service 'entity_type.bundle.info'
$bundle = $entity_type_id;
$bundle_entity_type = $this->entityTypeManager->getDefinition($entity_type_id)->getBundleEntityType();
if (NULL !== $bundle_entity_type) {
$bundle_list = $this->entityTypeManager->getStorage($bundle_entity_type)->loadMultiple();
if (count($bundle_list) > 0) {
foreach ($bundle_list as $bundle_entity) {
$bundle_to_test = (string) $bundle_entity->id();
$definitions = $this->entityFieldManager->getFieldDefinitions($entity_type_id, $bundle_to_test);
if (array_key_exists($field_name, $definitions)) {
$bundle = $bundle_to_test;
break;
}
}
}
}
return $bundle;
}
/**
* Set the context of field and entity (override the method trait).
*
......@@ -159,14 +226,15 @@ abstract class ComponentFormatterBase extends FormatterBase {
// When field items are available, we can get the entity directly.
$entity = ($items) ? $items->getEntity() : NULL;
if (!$entity) {
$entity = $this->contextHelper->guessEntity($contexts);
$entity = $this->chainContextEntityResolver->guessEntity($contexts);
}
if (!$entity || !$this->contextHelper->checkEntityHasField($entity, $entity_type_id, $field_name)) {
if (!$entity || !$this->checkEntityHasField($entity, $entity_type_id, $field_name)) {
// Generate a default bundle when it is missing,
// this covers contexts like the display of a field in a view.
// the bundle selected should have the field in definition...
$entity = !empty($bundle) ? $this->contextHelper->getSampleEntity($entity_type_id, $bundle) :
$this->contextHelper->getSampleEntityWithField($entity_type_id, $field_name);
$entity = !empty($bundle) ? $this->sampleEntityGenerator->get($entity_type_id, $bundle) :
$this->sampleEntityGenerator->get($entity_type_id, $this->findEntityBundleWithField($entity_type_id, $field_name));
}
$contexts['entity'] = EntityContext::fromEntity($entity);
return $contexts;
......
......@@ -13,8 +13,8 @@ use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextDefinition;
use Drupal\Core\Plugin\Context\EntityContext;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\ui_patterns\ContextHelperInterface;
use Drupal\ui_patterns\Form\ComponentFormBuilderTrait;
use Drupal\ui_patterns\Resolver\ChainContextEntityResolverInterface;
use Drupal\ui_patterns\SourcePluginBase;
use Drupal\ui_patterns_layouts\Plugin\Derivative\ComponentLayout as DerivativeComponentLayout;
use Symfony\Component\DependencyInjection\ContainerInterface;
......@@ -39,14 +39,14 @@ class ComponentLayout extends LayoutDefault implements ContainerFactoryPluginInt
* The plugin ID for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\ui_patterns\ContextHelperInterface $contextHelper
* @param \Drupal\ui_patterns\Resolver\ChainContextEntityResolverInterface $chainContextEntityResolver
* The context helper.
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
protected ContextHelperInterface $contextHelper,
protected ChainContextEntityResolverInterface $chainContextEntityResolver,
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
......@@ -59,7 +59,7 @@ class ComponentLayout extends LayoutDefault implements ContainerFactoryPluginInt
$configuration,
$plugin_id,
$plugin_definition,
$container->get('ui_patterns.context_helper')
$container->get('ui_patterns.chain_context_entity_resolver')
);
return $plugin;
}
......@@ -98,10 +98,12 @@ class ComponentLayout extends LayoutDefault implements ContainerFactoryPluginInt
* Source contexts.
*/
protected function getComponentSourceContexts(FormStateInterface $form_state = NULL): array {
$gatheredContexts = $form_state ? $form_state->getTemporaryValue('gathered_contexts') : [];
$this->contextHelper->applyContextMapping($this, $gatheredContexts ?: []);
if (!isset($this->context['entity']) || !($this->context['entity']->getContextValue() instanceof EntityInterface)) {
if ($entity = $this->contextHelper->guessEntity($this->context, $form_state)) {
$contexts = $this->context;
if ($form_state !== NULL) {
$contexts['ui_patterns:form_state'] = new Context(ContextDefinition::create('any'), $form_state);
}
if ($entity = $this->chainContextEntityResolver->guessEntity($contexts)) {
$this->context['entity'] = EntityContext::fromEntity($entity);
}
}
......
<?php
declare(strict_types=1);
namespace Drupal\ui_patterns;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
/**
* Interface for Context helper used by drupal plugins.
*/
interface ContextHelperInterface {
/**
* Get an entity from contexts.
*
* @param array<mixed> $contexts
* Known contexts.
* @param \Drupal\Core\Form\FormStateInterface|null $form_state
* Optional Form state.
*
* @return \Drupal\Core\Entity\EntityInterface|null
* Entity or null.
*/
public function guessEntity(array $contexts = [], FormStateInterface $form_state = NULL): ?EntityInterface;
/**
* Check if the entity is compatible with the field.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity.
* @param string $entity_type_id
* The entity type id.
* @param string $field_name
* The field name.
*
* @return bool
* TRUE if the entity is compatible.
*/
public function checkEntityHasField(EntityInterface $entity, string $entity_type_id, string $field_name) : bool;
/**
* Return an entity of the desired type.
*
* @param string $entity_type_id
* The entity type id.
* @param string $bundle
* The bundle.
*
* @return \Drupal\Core\Entity\EntityInterface
* The entity.
*/
public function getSampleEntity(string $entity_type_id, string $bundle) : EntityInterface;
/**
* Get an entity with the desired field.
*
* @param string $entity_type_id
* The entity type id.
* @param string $field_name
* The field name.
*
* @return \Drupal\Core\Entity\EntityInterface
* The entity with the field.
*/
public function getSampleEntityWithField(string $entity_type_id, string $field_name) : EntityInterface;
/**
* Apply context mapping to a plugin.
*
* @param \Drupal\Core\Plugin\ContextAwarePluginInterface $plugin
* The plugin to apply context mapping to.
* @param array $gathered_contexts
* Contexts to use in addition to contexts from contextRepository.
*/
public function applyContextMapping(ContextAwarePluginInterface $plugin, array $gathered_contexts = []) : void;
}
......@@ -6,6 +6,8 @@ namespace Drupal\ui_patterns\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\SubformState;
use Drupal\Core\Plugin\Context\ContextHandler;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
use Drupal\Core\Url;
/**
......@@ -175,6 +177,26 @@ trait ComponentFormBuilderTrait {
return \Drupal::service("ui_patterns.component_element_builder");
}
/**
* Wraps the context repository.
*
* @return \Drupal\Core\Plugin\Context\ContextRepositoryInterface
* The context repository.
*/
protected function contextRepository(): ContextRepositoryInterface {
return \Drupal::service('context.repository');
}
/**
* Wraps the context handler.
*
* @return \Drupal\Core\Plugin\Context\ContextHandler
* The context handler.
*/
protected function contextHandler(): ContextHandler {
return \Drupal::service('context.handler');
}
/**
* Calculate a component dependencies.
*
......
<?php
namespace Drupal\ui_patterns\Resolver;
use Drupal\Core\Entity\EntityInterface;
/**
* Default implementation of the chain base context entity resolver.
*/
class ChainContextEntityResolver implements ChainContextEntityResolverInterface {
/**
* The resolvers.
*
* @var \Drupal\ui_patterns\Resolver\ContextEntityResolverInterface[]
*/
protected $resolvers = [];
/**
* Constructs a new ChainBasePriceResolver object.
*
* @param \Drupal\ui_patterns\Resolver\ContextEntityResolverInterface[] $resolvers
* The resolvers.
*/
public function __construct(array $resolvers = []) {
$this->resolvers = $resolvers;
}
/**
* {@inheritdoc}
*/
public function addResolver(ContextEntityResolverInterface $resolver): void {
$this->resolvers[] = $resolver;
}
/**
* {@inheritdoc}
*/
public function getResolvers():array {
return $this->resolvers;
}
/**
* {@inheritdoc}
*/
public function guessEntity(array $contexts = []): ?EntityInterface {
foreach ($this->resolvers as $resolver) {
$result = $resolver->guessEntity($contexts);
if ($result) {
return $result;
}
}
return NULL;
}
}
<?php
namespace Drupal\ui_patterns\Resolver;
/**
* Runs the added resolvers one by one until one of them returns an Entity.
*
* Each resolver in the chain can be another chain, which is why this interface
* extends the base context resolver one.
*/
interface ChainContextEntityResolverInterface extends ContextEntityResolverInterface {
/**
* Adds a resolver.
*
* @param \Drupal\ui_patterns\Resolver\ContextEntityResolverInterface $resolver
* The resolver.
*/
public function addResolver(ContextEntityResolverInterface $resolver):void;
/**
* Gets all added resolvers.
*
* @return \Drupal\ui_patterns\Resolver\ContextEntityResolverInterface[]
* The resolvers.
*/
public function getResolvers(): array;
}
<?php
namespace Drupal\ui_patterns\Resolver;
use Drupal\Core\Entity\EntityInterface;
/**
* Defines the interface for context entity resolvers.
*/
interface ContextEntityResolverInterface {
/**
* Get an entity from contexts.
*
* @param array<mixed> $contexts
* Known contexts.
*
* @return \Drupal\Core\Entity\EntityInterface|null
* Entity or null.
*/
public function guessEntity(array $contexts = []): ?EntityInterface;
}
<?php
namespace Drupal\ui_patterns\Resolver;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\field_layout\Entity\FieldLayoutEntityFormDisplay;
use Drupal\field_layout\Entity\FieldLayoutEntityViewDisplay;
use Drupal\field_layout\Form\FieldLayoutEntityFormDisplayEditForm;
use Drupal\field_layout\Form\FieldLayoutEntityViewDisplayEditForm;
use Drupal\ui_patterns\Entity\SampleEntityGeneratorInterface;
/**
* Provides context entity for field layouts.
*/
class FieldLayoutContextEntityResolver implements ContextEntityResolverInterface {
/**
* {@inheritdoc}
*/
public function __construct(
protected EntityTypeManagerInterface $entityTypeManager,
protected SampleEntityGeneratorInterface $sampleEntityGenerator,
) {
}
/**
* {@inheritdoc}
*/
public function guessEntity(array $contexts = []): ?EntityInterface {
$form_state = isset($contexts['ui_patterns:form_state']) ? $contexts['ui_patterns:form_state']->getContextValue() : NULL;
if ($entity = $this->guessFieldLayoutEntity($form_state)) {
return $entity;
}
return NULL;
}
/**
* Guess the entity from the field layout form.
*
* @param \Drupal\Core\Form\FormStateInterface|null $form_state
* Optional Form state.
*
* @return \Drupal\Core\Entity\EntityInterface|null
* The entity if found or null.
*/
protected function guessFieldLayoutEntity(?FormStateInterface $form_state = NULL) : ?EntityInterface {
if ($form_state !== NULL) {
$form_object = $form_state->getFormObject();
if (($form_object instanceof FieldLayoutEntityViewDisplayEditForm) ||
($form_object instanceof FieldLayoutEntityFormDisplayEditForm)) {
$entity = $form_object->getEntity();
if (($entity instanceof FieldLayoutEntityViewDisplay)|| ($entity instanceof FieldLayoutEntityFormDisplay)) {
return $this->sampleEntityGenerator->get($entity->getTargetEntityTypeId(), $entity->getTargetBundle());
}
}
}
return NULL;
}
}
<?php
declare(strict_types=1);
namespace Drupal\ui_patterns\Resolver;
namespace Drupal\ui_patterns;
use Drupal\Component\Plugin\Exception\ContextException;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\Context\ContextHandlerInterface;
use Drupal\Core\Plugin\Context\ContextInterface;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
use Drupal\Core\Plugin\Context\EntityContext;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\field_layout\Entity\FieldLayoutEntityFormDisplay;
use Drupal\field_layout\Entity\FieldLayoutEntityViewDisplay;
use Drupal\field_layout\Form\FieldLayoutEntityFormDisplayEditForm;
use Drupal\field_layout\Form\FieldLayoutEntityViewDisplayEditForm;
use Drupal\layout_builder\DefaultsSectionStorageInterface;
use Drupal\layout_builder\Form\ConfigureSectionForm;
use Drupal\layout_builder\OverridesSectionStorageInterface;
......@@ -28,114 +15,32 @@ use Drupal\layout_builder\SectionStorageInterface;
use Drupal\ui_patterns\Entity\SampleEntityGeneratorInterface;
/**
* Context helper used by drupal plugins to get the context.
* Provides context entity for layout builder.
*/
class ContextHelper implements ContextHelperInterface {
class LayoutBuilderContextEntityResolver implements ContextEntityResolverInterface {
/**
* {@inheritdoc}
*/
public function __construct(
protected SampleEntityGeneratorInterface $sampleEntityGenerator,
protected ContextRepositoryInterface $contextRepository,
protected ContextHandlerInterface $contextHandler,
protected ModuleHandlerInterface $moduleHandler,
protected RouteMatchInterface $routeMatch,
protected EntityTypeManagerInterface $entityTypeManager,
protected EntityFieldManagerInterface $entityFieldManager,
protected SampleEntityGeneratorInterface $sampleEntityGenerator,
) {
}
/**
* {@inheritdoc}
*/
public function guessEntity(array $contexts = [], FormStateInterface $form_state = NULL): ?EntityInterface {
if ($this->moduleHandler->moduleExists("layout_builder")) {
// Try to get the $section storage.
$section_storage = $this->getLayoutBuilderSectionStorage($form_state);
if ($section_storage && ($entity = $this->guessLayoutBuilderEntity($section_storage))) {
return $entity;
}
}
if ($this->moduleHandler->moduleExists("field_layout")) {
if ($entity = $this->guessFieldLayoutEntity($form_state)) {
return $entity;
}
public function guessEntity(array $contexts = []): ?EntityInterface {
$form_state = isset($contexts['ui_patterns:form_state']) ? $contexts['ui_patterns:form_state']->getContextValue() : NULL;
$section_storage = $this->getLayoutBuilderSectionStorage($form_state);
if ($section_storage && ($entity = $this->guessLayoutBuilderEntity($section_storage))) {
return $entity;
}
return NULL;
}
/**
* {@inheritdoc}
*/
public function getSampleEntity(string $entity_type_id, string $bundle) : EntityInterface {
return $this->sampleEntityGenerator->get($entity_type_id, $bundle);
}
/**
* {@inheritdoc}
*/
public function getSampleEntityWithField(string $entity_type_id, string $field_name) : EntityInterface {
return $this->getSampleEntity($entity_type_id, $this->findEntityBundleWithField($entity_type_id, $field_name));
}
/**
* {@inheritdoc}
*/
public function checkEntityHasField(EntityInterface $entity, string $entity_type_id, string $field_name) : bool {
$field_definitions = $this->entityFieldManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle());
return ($entity->getEntityTypeId() === $entity_type_id &&
array_key_exists($field_name, $field_definitions));
}
/**
* Find an entity bundle which has a field.
*
* @param string $entity_type_id
* The entity type id.
* @param string $field_name
* The field name to be found in searched bundle.
*
* @return string
* The bundle.
*/
public function findEntityBundleWithField(string $entity_type_id, string $field_name) : string {
// @todo better implementation with service 'entity_type.bundle.info'
$bundle = $entity_type_id;
$bundle_entity_type = $this->entityTypeManager->getDefinition($entity_type_id)->getBundleEntityType();
if (NULL !== $bundle_entity_type) {
$bundle_list = $this->entityTypeManager->getStorage($bundle_entity_type)->loadMultiple();
if (count($bundle_list) > 0) {
foreach ($bundle_list as $bundle_entity) {
$bundle_to_test = (string) $bundle_entity->id();
$definitions = $this->entityFieldManager->getFieldDefinitions($entity_type_id, $bundle_to_test);
if (array_key_exists($field_name, $definitions)) {
$bundle = $bundle_to_test;
break;
}
}
}
}
return $bundle;
}
/**
* {@inheritdoc}
*/
public function applyContextMapping(ContextAwarePluginInterface $plugin, array $gathered_contexts = []) : void {
$available_contexts = $this->contextRepository->getAvailableContexts();
if (!is_array($gathered_contexts)) {
$gathered_contexts = [];
}
if (!empty($gathered_contexts)) {
$gathered_contexts = array_filter($gathered_contexts, fn($context) => $context instanceof ContextInterface);
$available_contexts = array_merge($available_contexts, $gathered_contexts);
}
try {
$this->contextHandler->applyContextMapping($plugin, $available_contexts);
}
catch (ContextException $e) {
// Do nothing.
}
}
/**
* Gets the layout builder section storage.
*
......@@ -214,27 +119,4 @@ class ContextHelper implements ContextHelperInterface {
return NULL;
}
/**
* Guess the entity from the field layout form.
*
* @param \Drupal\Core\Form\FormStateInterface|null $form_state
* Optional Form state.
*
* @return \Drupal\Core\Entity\EntityInterface|null
* The entity if found or null.
*/
protected function guessFieldLayoutEntity(?FormStateInterface $form_state = NULL) : ?EntityInterface {
if ($form_state !== NULL) {
$form_object = $form_state->getFormObject();
if (($form_object instanceof FieldLayoutEntityViewDisplayEditForm) ||
($form_object instanceof FieldLayoutEntityFormDisplayEditForm)) {
$entity = $form_object->getEntity();
if (($entity instanceof FieldLayoutEntityViewDisplay)|| ($entity instanceof FieldLayoutEntityFormDisplay)) {
return $this->getSampleEntity($entity->getTargetEntityTypeId(), $entity->getTargetBundle());
}
}
}
return NULL;
}
}
<?php
namespace Drupal\ui_patterns;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Symfony\Component\DependencyInjection\Reference;
/**
* Registers layout builder and field layout resolver.
*/
class UiPatternsServiceProvider extends ServiceProviderBase {
/**
* {@inheritdoc}
*/
public function register(ContainerBuilder $container): void {
$modules = $container->getParameterBag()->get('container.modules');
if (is_array($modules) === FALSE) {
return;
}
if (isset($modules['layout_builder'])) {
$service = $container->register('ui_patterns.layout_builder_context_entity_resolver', '\Drupal\ui_patterns\Resolver\LayoutBuilderContextEntityResolver');
$service->addArgument(new Reference('current_route_match'));
$service->addArgument(new Reference('entity_type.manager'));
$service->addArgument(new Reference('ui_patterns.sample_entity_generator'));
$service->addTag('ui_patterns.context_entity_resolver', ['priority' => 10]);
}
if (isset($modules['field_layout'])) {
$service = $container->register('ui_patterns.field_layout_context_entity_resolver', '\Drupal\ui_patterns\Resolver\FieldLayoutContextEntityResolver');
$service->addArgument(new Reference('entity_type.manager'));
$service->addArgument(new Reference('ui_patterns.sample_entity_generator'));
$service->addTag('ui_patterns.context_entity_resolver', ['priority' => 20]);
}
}
}
<?php
namespace Drupal\ui_patterns_test\Resolver;
use Drupal\Core\Entity\EntityInterface;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\ui_patterns\Resolver\ContextEntityResolverInterface;
/**
* Test implementation of the context entity resolver.
*/
class TestContextEntityResolver implements ContextEntityResolverInterface {
/**
* {@inheritdoc}
*/
public function guessEntity(array $contexts = []): ?EntityInterface {
if (isset($contexts['ui_patterns:test'])) {
$entity = EntityTest::create();
$entity->save();
return $entity;
}
return NULL;
}
}
services:
ui_patterns_test.test_context_entity_resolver:
class: Drupal\ui_patterns_test\Resolver\TestContextEntityResolver
tags:
- { name: ui_patterns.context_entity_resolver }
<?php
declare(strict_types=1);
namespace Drupal\Tests\ui_patterns\Kernel\Resolver;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextDefinition;
use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
use Drupal\ui_patterns\Resolver\ChainContextEntityResolver;
use Drupal\ui_patterns_test\Resolver\TestContextEntityResolver;
/**
* Test the ChainContextEntityResolver service.
*
* @coversDefaultClass \Drupal\ui_patterns\Resolver\ChainContextEntityResolver
*
* @group ui_patterns
*/
final class ChainContextEntityResolverTest extends EntityKernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['ui_patterns', 'ui_patterns_test'];
/**
* The chain context entity resolver.
*/
protected ChainContextEntityResolver $chainContextEntityResolver;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->chainContextEntityResolver = \Drupal::service('ui_patterns.chain_context_entity_resolver');
}
/**
* @covers ::getResolvers
*/
public function testGetResolvers() : void {
$resolvers = $this->chainContextEntityResolver->getResolvers();
$test_resolver = NULL;
foreach ($resolvers as $resolver) {
if ($resolver instanceof TestContextEntityResolver) {
$test_resolver = $resolver;
}
}
$this->assertNotNull($test_resolver);
}
/**
* @covers ::guessEntity
*/
public function testGuessEntity() : void {
$contexts['ui_patterns:test'] = new Context(ContextDefinition::create('any'), TRUE);
$entity = $this->chainContextEntityResolver->guessEntity($contexts);
$this->assertNotNull($entity);
}
}
......@@ -84,13 +84,8 @@ services:
arguments: ["@plugin.manager.ui_patterns_source"]
tags:
- { name: "event_subscriber" }
ui_patterns.context_helper:
class: Drupal\ui_patterns\ContextHelper
arguments:
- "@ui_patterns.sample_entity_generator"
- "@context.repository"
- "@context.handler"
- "@module_handler"
- "@current_route_match"
- "@entity_type.manager"
- "@entity_field.manager"
ui_patterns.chain_context_entity_resolver:
class: Drupal\ui_patterns\Resolver\ChainContextEntityResolver
tags:
- { name: service_collector, call: addResolver, tag: ui_patterns.context_entity_resolver }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment