commands-1.x-dev/modules/tasks/src/Plugin/Validation/Constraint/TaskCommandsCreateConstraintValidator.php

modules/tasks/src/Plugin/Validation/Constraint/TaskCommandsCreateConstraintValidator.php
<?php

declare(strict_types=1);

namespace Drupal\tasks\Plugin\Validation\Constraint;

use Drupal\commands\Entity\Command;
use Drupal\Core\Entity\EntityInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the TaskCommandsCreate constraint.
 */
final class TaskCommandsCreateConstraintValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate(mixed $entity, Constraint $constraint): void {
    if (!$entity instanceof EntityInterface) {
      throw new \InvalidArgumentException(
        sprintf('The validated value must be instance of \Drupal\Core\Entity\EntityInterface, %s was given.', get_debug_type($entity))
      );
    }

    // Create new Commands from $entity->commands array (which should be command_type strings).
    foreach ($entity->commands as $command_field) {
      $command_entity_data = $command_field->getValue();

      try {
        $command = Command::create($command_entity_data);
        $command->save();
        $command_field_value[] = [
          'target_id' => $command->id(),
        ];
      }
      catch (\Exception $e) {
        $this->context->buildViolation(t('Unable to create command entity. The error was: :error', [
          ':error' => $e->getMessage(),
        ]))
          ->atPath('commands')
          ->addViolation();
      }
    }

    $entity->set('commands', $command_field_value);

  }
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc