component_library-1.0.x-dev/src/EventSubscriber/PrepareOverrideBase.php
src/EventSubscriber/PrepareOverrideBase.php
<?php
declare(strict_types=1);
namespace Drupal\component_library\EventSubscriber;
use Drupal\component_library\Event\PrepareOverrideEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Prepare override base.
*/
abstract class PrepareOverrideBase implements EventSubscriberInterface {
/**
* Has been processed.
*
* @var bool
* Whether this event has been processed.
*/
protected bool $hasBeenProcessed = FALSE;
/**
* On Prepare Override.
*
* This event is dispatched multiple times. EventSubscribers should call
* overridePrepared() once the event has been completed to prevent subsequent
* executions.
*
* @param \Drupal\component_library\Event\PrepareOverrideEvent $event
* The prepare override event.
*/
abstract protected function onPrepareOverride(PrepareOverrideEvent $event): void;
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events = [];
$events[PrepareOverrideEvent::class][] = ['runOnce'];
return $events;
}
/**
* Override prepared.
*
* Flags that this event has been processed to prevent subsequent executions.
*/
protected function overridePrepared(): void {
$this->hasBeenProcessed = TRUE;
}
/**
* Run once.
*
* Ensure that onPrepareOverride is only computed once for each event since it
* is dispatched multiple times.
*
* @param \Drupal\component_library\Event\PrepareOverrideEvent $event
* The event.
*/
public function runOnce(PrepareOverrideEvent $event): void {
if (!$this->hasBeenProcessed) {
$this->onPrepareOverride($event);
}
}
}
