a12s-1.0.0-beta7/modules/page_context/src/Plugin/A12sPageContextFormDisplay/Entity.php
modules/page_context/src/Plugin/A12sPageContextFormDisplay/Entity.php
<?php
namespace Drupal\a12s_page_context\Plugin\A12sPageContextFormDisplay;
use Drupal\a12s_core\EntityHelperInterface;
use Drupal\a12s_page_context\Entity\PageContextForm;
use Drupal\a12s_page_context\Entity\PageContextFormInterface;
use Drupal\a12s_page_context\Plugin\FormDisplayPluginBase;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\SubformStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Plugin implementation of the a12s_page_context_form.
*
* @A12sPageContextFormDisplay(
* id = "entity",
* label = @Translation("Entity"),
* description = @Translation("Display the form on some entity edit pages"),
* )
*
* @noinspection AnnotationMissingUseInspection
*/
class Entity extends FormDisplayPluginBase implements ContainerFactoryPluginInterface {
use StringTranslationTrait;
/**
* {@inheritdoc}
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
* The entity type manager.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundleInfoService
* The bundle info service.
* @param \Drupal\a12s_core\EntityHelperInterface $entityHelper
* The Entity Helper service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, protected EntityTypeManagerInterface $entityTypeManager, protected EntityTypeBundleInfoInterface $bundleInfoService, protected EntityHelperInterface $entityHelper) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
/**
* {@inheritdoc}
* @noinspection PhpParamsInspection
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
return new static($configuration, $plugin_id, $plugin_definition,
$container->get('entity_type.manager'),
$container->get('entity_type.bundle.info'),
$container->get('a12s_core.entity_helper')
);
}
/**
* {@inheritdoc}
*/
public function applies(array $context): bool {
if (!isset($context['entity']) || !$context['entity'] instanceof EntityInterface) {
return FALSE;
}
$entityTypeId = $context['entity']->getEntityTypeId();
if (!isset($this->configuration['entity_types'][$entityTypeId])) {
return FALSE;
}
$entityType = $context['entity']->getEntityType();
if (!$entityType->entityClassImplements(ContentEntityInterface::class)) {
return FALSE;
}
$bundleInfo = $this->bundleInfoService->getBundleInfo($entityTypeId);
if (count($bundleInfo) > 1 || $entityType->getKey('bundle')) {
$bundles = $this->configuration['entity_types'][$entityTypeId] ?? [];
if (!empty($bundles) && !in_array($context['entity']->bundle(), $bundles)) {
return FALSE;
}
}
return TRUE;
}
/**
* {@inheritdoc}
*/
public function getCurrentContext(array $context = []): array {
$context += ['rel' => 'canonical'];
if (!array_key_exists('entity', $context)) {
$context['entity'] = $this->entityHelper->getEntityFromRoute($context['rel']);
}
return $context;
}
/**
* {@inheritdoc}
*/
public function getStorageKey(array $context): ?string {
if (isset($context['entity']) && $context['entity'] instanceof EntityInterface) {
return $context['entity']->getEntityTypeId() . ':' . $context['entity']->id();
}
return NULL;
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration(): array {
return [
'entity_types' => [],
];
}
/**
* {@inheritdoc}
*/
public function setConfigurationFromFormInput(array $input): void {
$raw = $input['entity_types'] ?? [];
$entityTypes = [];
foreach (array_keys(array_filter($raw)) as $entityType) {
$entityTypes[$entityType] = [];
if (!empty($input['bundles'][$entityType])) {
$entityTypes[$entityType] = array_values(array_filter($input['bundles'][$entityType]));
}
}
$this->configuration = ['entity_types' => $entityTypes];
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface|SubformStateInterface $form_state): array {
$form = parent::buildConfigurationForm($form, $form_state);
$formParents = $form['#parents'] ?? [];
$form['#description'] = $this->t('The form is applied to all bundles when there is nothing selected.');
foreach ($this->entityTypeManager->getDefinitions() as $entityTypeId => $entityType) {
if ($entityType->entityClassImplements(ContentEntityInterface::class)) {
$form[$entityTypeId] = [
'#type' => 'container',
// @todo add CSS styles for this options.
// '#attributes' => [ 'class' => ['???'], ],
];
$form[$entityTypeId]['enabled'] = [
'#type' => 'checkbox',
'#title' => $entityType->getLabel(),
'#parents' => array_merge($formParents, ['entity_types', $entityTypeId]),
'#default_value' => isset($this->configuration['entity_types'][$entityTypeId]),
];
$bundleOptions = [];
$bundleInfo = $this->bundleInfoService->getBundleInfo($entityTypeId);
if (count($bundleInfo) > 1 || $entityType->getKey('bundle')) {
foreach ($bundleInfo as $bundle => $info) {
$bundleOptions[$bundle] = $info['label'];
}
$parents = array_merge($formParents, ['entity_types', $entityTypeId]);
$form[$entityTypeId]['bundles'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Bundles'),
'#title_display' => 'invisible',
'#options' => $bundleOptions,
'#parents' => array_merge($formParents, ['bundles', $entityTypeId]),
'#default_value' => $this->configuration['entity_types'][$entityTypeId] ?? [],
'#states' => [
'visible' => [
':input[name="' . array_shift($parents) . '[' . implode('][', $parents) . ']"]' => ['checked' => TRUE],
],
],
];
}
}
}
return $form;
}
/**
* {@inheritdoc}
*/
public function alterContextForm(PageContextFormInterface $pageContextForm, array $context, array &$form, FormStateInterface $form_state, array $parents = ['a12s_page_context']): void {
parent::alterContextForm($pageContextForm, $context, $form, $form_state, $parents);
if (NestedArray::keyExists($form, $parents)) {
// For entities, we need to add our submit callback to the submit button.
$form['actions']['submit']['#submit'][] = [PageContextForm::class, 'saveRecord'];
if ($context['entity']?->getEntityTypeId() === 'node') {
$form['a12s_page_context']['#type'] = 'details';
$form['a12s_page_context']['#group'] = 'advanced';
$form['a12s_page_context']['#open'] = FALSE;
$form['a12s_page_context']['#weight'] = 10;
// @todo Add permission and check access?
}
}
}
}
