component_library-1.0.x-dev/src/EventSubscriber/EntityYamlPlaceholders.php
src/EventSubscriber/EntityYamlPlaceholders.php
<?php
declare(strict_types=1);
namespace Drupal\component_library\EventSubscriber;
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\component_library\Event\ConvertYamlPlaceholdersEvent;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Logger\LoggerChannelInterface;
use Drupal\Core\Utility\Error;
use Drupal\layout_builder\Entity\SampleEntityGeneratorInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final class EntityYamlPlaceholders implements EventSubscriberInterface {
private SampleEntityGeneratorInterface $generator;
private LoggerChannelInterface $logger;
public static function getSubscribedEvents(): array {
return [
ConvertYamlPlaceholdersEvent::class => ['onConvertYamlPlaceholders', 100],
];
}
public function __construct(SampleEntityGeneratorInterface $generator, LoggerChannelInterface $logger) {
$this->generator = $generator;
$this->logger = $logger;
}
public function onConvertYamlPlaceholders(ConvertYamlPlaceholdersEvent $event): void {
foreach ($event->getContext() as $key => $value) {
if (\is_string($value) && \str_starts_with($value, 'content_entity:')) {
$values = \explode(':', $value);
if (\count($values) !== 3) {
// This isn't an entity, so don't set the context item.
continue;
}
[, $entity_type, $bundle] = $values;
try {
$sample_entity = $this->generator->get($entity_type, $bundle);
$event->setContextItem($key, $sample_entity);
}
catch (\InvalidArgumentException | PluginNotFoundException | InvalidPluginDefinitionException | EntityStorageException $exception) {
$this->logException($exception);
}
}
}
}
private function logException(\Exception $exception): void {
$message = '%type: @message in %function (line %line of %file).';
$variables = Error::decodeException($exception);
$this->logger->error($message, $variables);
}
}
