ModerationStateValidator.php in Workbench Moderation 8.2
File
src/Plugin/Validation/Constraint/ModerationStateValidator.php
View source
<?php
namespace Drupal\workbench_moderation\Plugin\Validation\Constraint;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\workbench_moderation\ModerationInformationInterface;
use Drupal\workbench_moderation\StateTransitionValidation;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ModerationStateValidator extends ConstraintValidator implements ContainerInjectionInterface {
protected $validation;
private $entityTypeManager;
protected $moderationInformation;
public function __construct(EntityTypeManagerInterface $entity_type_manager, StateTransitionValidation $validation, ModerationInformationInterface $moderation_information) {
$this->validation = $validation;
$this->entityTypeManager = $entity_type_manager;
$this->moderationInformation = $moderation_information;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager'), $container
->get('workbench_moderation.state_transition_validation'), $container
->get('workbench_moderation.moderation_information'));
}
public function validate($value, Constraint $constraint) {
$entity = $value
->getEntity();
if (!$this->moderationInformation
->isModeratableEntity($entity)) {
return;
}
if ($entity
->isNew()) {
return;
}
if ($this
->isFirstTimeModeration($entity)) {
return;
}
$original_entity = $this->moderationInformation
->getLatestRevision($entity
->getEntityTypeId(), $entity
->id());
if (!$entity
->isDefaultTranslation() && $original_entity
->hasTranslation($entity
->language()
->getId())) {
$original_entity = $original_entity
->getTranslation($entity
->language()
->getId());
}
$next_moderation_state_id = $entity->moderation_state->target_id;
$original_moderation_state_id = $original_entity->moderation_state->target_id;
if (!$this->validation
->isTransitionAllowed($original_moderation_state_id, $next_moderation_state_id)) {
$this->context
->addViolation($constraint->message, [
'%from' => $original_entity->moderation_state->entity
->label(),
'%to' => $entity->moderation_state->entity
->label(),
]);
}
}
protected function isFirstTimeModeration(EntityInterface $entity) {
$original_entity = $this->moderationInformation
->getLatestRevision($entity
->getEntityTypeId(), $entity
->id());
$original_id = $original_entity->moderation_state->target_id;
return !($entity->moderation_state->target_id && $original_entity && $original_id);
}
}