<?php
namespace Drupal\my_extension\Plugin\EbOperation;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\eb\Attribute\EbOperation;
use Drupal\eb\Exception\ExecutionException;
use Drupal\eb\PluginBase\OperationBase;
use Drupal\eb\Result\ExecutionResult;
use Drupal\eb\Result\PreviewResult;
use Drupal\eb\Result\RollbackResult;
use Drupal\eb\Result\ValidationResult;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Operation for creating My Entity.
*/
#[EbOperation(
id: 'create_my_entity',
label: new TranslatableMarkup('Create My Entity'),
description: new TranslatableMarkup('Creates a My Entity configuration'),
operationType: 'create',
)]
class CreateMyEntityOperation extends OperationBase implements ContainerFactoryPluginInterface {
/**
* My custom service.
*/
protected $myService;
/**
* {@inheritdoc}
*/
public function __construct(
array $configuration,
string $plugin_id,
mixed $plugin_definition,
EntityTypeManagerInterface $entityTypeManager,
LoggerInterface $logger,
$myService,
) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $entityTypeManager, $logger);
$this->myService = $myService;
}
/**
* {@inheritdoc}
*/
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('logger.channel.eb'),
$container->get('my_service'),
);
}
/**
* {@inheritdoc}
*/
public function validate(): ValidationResult {
$result = new ValidationResult();
$this->validateRequiredFields(['entity_type', 'bundle', 'entity_id'], $result);
if (!$result->isValid()) {
return $result;
}
// Custom validation
$entityId = $this->getDataValue('entity_id');
if (!preg_match('/^[a-z_]+$/', $entityId)) {
$result->addError(
'Entity ID must be lowercase with underscores only.',
'entity_id',
'invalid_entity_id'
);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function preview(): PreviewResult {
$preview = new PreviewResult();
$entityId = $this->getDataValue('entity_id');
$label = $this->getDataValue('label', $entityId);
$preview->addOperation(
'create',
'my_entity',
$entityId,
$this->t('Create My Entity "@label"', ['@label' => $label])
);
$preview->addDetails([
'Entity ID' => $entityId,
'Label' => $label,
'Entity Type' => $this->getDataValue('entity_type'),
'Bundle' => $this->getDataValue('bundle'),
]);
return $preview;
}
/**
* {@inheritdoc}
*/
public function execute(): ExecutionResult {
try {
$entityId = $this->getDataValue('entity_id');
$label = $this->getDataValue('label', $entityId);
$entityType = $this->getDataValue('entity_type');
$bundle = $this->getDataValue('bundle');
$settings = $this->getDataValue('settings', []);
// Create the entity using your service
$entity = $this->myService->create([
'id' => $entityId,
'label' => $label,
'entity_type' => $entityType,
'bundle' => $bundle,
'settings' => $settings,
]);
$entity->save();
$result = new ExecutionResult(TRUE);
$result->addMessage($this->t('My Entity "@label" created successfully.', [
'@label' => $label,
]));
$result->addAffectedEntity([
'type' => 'my_entity',
'id' => $entityId,
'label' => $label,
]);
// Store rollback data
$result->setRollbackData([
'entity_id' => $entityId,
'was_new' => TRUE,
]);
$this->logger->info('Created My Entity: @id', ['@id' => $entityId]);
return $result;
}
catch (\Exception $e) {
$this->logger->error('My Entity creation failed: @message', [
'@message' => $e->getMessage(),
]);
throw new ExecutionException($e->getMessage(), [], 0, $e);
}
}
/**
* {@inheritdoc}
*/
public function rollback(): RollbackResult {
$rollbackData = $this->getDataValue('_rollback_data', []);
$entityId = $rollbackData['entity_id'] ?? $this->getDataValue('entity_id');
$wasNew = $rollbackData['was_new'] ?? FALSE;
if ($wasNew) {
// Delete the newly created entity
$entity = $this->myService->load($entityId);
if ($entity) {
$entity->delete();
}
$result = new RollbackResult(TRUE);
$result->addMessage($this->t('My Entity "@id" deleted.', ['@id' => $entityId]));
}
else {
$result = new RollbackResult(FALSE);
$result->addMessage($this->t('No rollback data available for "@id".', ['@id' => $entityId]));
}
$result->addRestoredEntity([
'type' => 'my_entity',
'id' => $entityId,
]);
return $result;
}
}