component_library-1.0.x-dev/src/Plugin/ComponentOverride/ComponentOverrideBase.php
src/Plugin/ComponentOverride/ComponentOverrideBase.php
<?php
declare(strict_types=1);
namespace Drupal\component_library\Plugin\ComponentOverride;
use Drupal\Component\Serialization\Json;
use Drupal\component_library\ComponentOverrideManager;
use Drupal\component_library\Entity\ComponentOverride;
use Drupal\component_library\Event\PrepareOverrideEvent;
use Drupal\component_library\Form\ComponentOverrideFormTrait;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\PluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Base class for Component Override plugins.
*/
abstract class ComponentOverrideBase extends PluginBase implements ComponentOverrideInterface, ContainerFactoryPluginInterface {
use ComponentOverrideFormTrait;
protected ComponentOverride $override;
protected ComponentOverrideManager $overrideManager;
protected EventDispatcherInterface $dispatcher;
public ?PrepareOverrideEvent $prepareOverrideEvent;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): self {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('plugin.manager.component_override'),
$container->get('event_dispatcher'),
);
}
public function __construct(array $configuration, $plugin_id, $plugin_definition, ComponentOverrideManager $override_manager, EventDispatcherInterface $event_dispatcher) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->overrideManager = $override_manager;
$this->dispatcher = $event_dispatcher;
$this->override = $configuration['override'];
$this->prepareOverrideEvent = $configuration['prepare_override_event'] ?? new PrepareOverrideEvent();
}
/**
* {@inheritdoc}
*/
public function validateConfigurationForm(array &$form, FormStateInterface $form_state): void {
// Validation is optional.
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state): void {
// Store any plugin data.
$override = $form_state->getFormObject()->getEntity();
$values = $form_state->getValues();
unset($values['plugin'], $values['override']);
$override->set('plugin_data', Json::encode($values));
}
/**
* {@inheritdoc}
*/
public function getPluginValue($key, ComponentOverride $override, ?FormStateInterface $form_state = NULL): ?string {
$value = NULL;
if ($form_state !== NULL) {
$value = $form_state->getValue($key);
}
if ($value === NULL) {
$value = $this->getValue($key, $override, $form_state);
}
return $value;
}
}
