ModerationStateConstraintValidator.php in Drupal 8
File
core/modules/content_moderation/src/Plugin/Validation/Constraint/ModerationStateConstraintValidator.php
View source
<?php
namespace Drupal\content_moderation\Plugin\Validation\Constraint;
use Drupal\content_moderation\StateTransitionValidationInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\content_moderation\ModerationInformationInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Validation\Plugin\Validation\Constraint\NotNullConstraint;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ModerationStateConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
private $entityTypeManager;
protected $moderationInformation;
protected $currentUser;
protected $stateTransitionValidation;
public function __construct(EntityTypeManagerInterface $entity_type_manager, ModerationInformationInterface $moderation_information, AccountInterface $current_user, StateTransitionValidationInterface $state_transition_validation) {
$this->entityTypeManager = $entity_type_manager;
$this->moderationInformation = $moderation_information;
$this->currentUser = $current_user;
$this->stateTransitionValidation = $state_transition_validation;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager'), $container
->get('content_moderation.moderation_information'), $container
->get('current_user'), $container
->get('content_moderation.state_transition_validation'));
}
public function validate($value, Constraint $constraint) {
$entity = $value
->getEntity();
if (!$this->moderationInformation
->isModeratedEntity($entity)) {
return;
}
if ($value
->isEmpty()) {
$this->context
->addViolation((new NotNullConstraint())->message);
return;
}
$workflow = $this->moderationInformation
->getWorkflowForEntity($entity);
if (!$workflow
->getTypePlugin()
->hasState($entity->moderation_state->value)) {
$this->context
->addViolation($constraint->invalidStateMessage, [
'%state' => $entity->moderation_state->value,
'%workflow' => $workflow
->label(),
]);
return;
}
$new_state = $workflow
->getTypePlugin()
->getState($entity->moderation_state->value);
$original_state = $this->moderationInformation
->getOriginalState($entity);
if (!$original_state
->canTransitionTo($new_state
->id())) {
$this->context
->addViolation($constraint->message, [
'%from' => $original_state
->label(),
'%to' => $new_state
->label(),
]);
}
else {
if (!$this->stateTransitionValidation
->isTransitionValid($workflow, $original_state, $new_state, $this->currentUser, $entity)) {
$this->context
->addViolation($constraint->invalidTransitionAccess, [
'%original_state' => $original_state
->label(),
'%new_state' => $new_state
->label(),
]);
}
}
}
}