You are here

public function WorkflowsFieldContraintValidator::validate in Workflows Field 2.x

Same name and namespace in other branches
  1. 8 src/Plugin/Validation/Constraint/WorkflowsFieldContraintValidator.php \Drupal\workflows_field\Plugin\Validation\Constraint\WorkflowsFieldContraintValidator::validate()

File

src/Plugin/Validation/Constraint/WorkflowsFieldContraintValidator.php, line 52

Class

WorkflowsFieldContraintValidator
Validates the workflows field.

Namespace

Drupal\workflows_field\Plugin\Validation\Constraint

Code

public function validate($field, Constraint $constraint) {

  /** @var \Drupal\workflows_field\Plugin\Field\FieldType\WorkflowsFieldItem $field */
  $entity = $field
    ->getEntity();
  $workflow_type = $field
    ->getWorkflow()
    ->getTypePlugin();

  // An entity can start its life in any state.
  if (!isset($field->value) || $entity
    ->isNew()) {
    return;
  }
  $original_entity = $this->entityTypeManager
    ->getStorage($entity
    ->getEntityTypeId())
    ->loadUnchanged($entity
    ->id());
  if (!$entity
    ->isDefaultTranslation() && $original_entity
    ->hasTranslation($entity
    ->language()
    ->getId())) {
    $original_entity = $original_entity
      ->getTranslation($entity
      ->language()
      ->getId());
  }
  $previous_state = $original_entity->{$field
    ->getFieldDefinition()
    ->getName()}->value;

  // The state does not have to change.
  if ($previous_state === $field->value) {
    return;
  }
  if (!$workflow_type
    ->hasTransitionFromStateToState($previous_state, $field->value)) {
    $this->context
      ->addViolation($constraint->message, [
      '%state' => $field->value,
      '%previous_state' => $previous_state,
    ]);
  }
  else {
    $transition = $workflow_type
      ->getTransitionFromStateToState($previous_state, $field->value);
    if (!$this->currentUser
      ->hasPermission(sprintf('use %s transition %s', $field
      ->getWorkflow()
      ->id(), $transition
      ->id()))) {
      $this->context
        ->addViolation($constraint->insufficientPermissionsTransition, [
        '%transition' => $transition
          ->label(),
      ]);
    }
  }
}