You are here

public function EntityWorkspaceConflictConstraintValidator::validate in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/workspaces/src/Plugin/Validation/Constraint/EntityWorkspaceConflictConstraintValidator.php \Drupal\workspaces\Plugin\Validation\Constraint\EntityWorkspaceConflictConstraintValidator::validate()

File

core/modules/workspaces/src/Plugin/Validation/Constraint/EntityWorkspaceConflictConstraintValidator.php, line 81

Class

EntityWorkspaceConflictConstraintValidator
Validates the EntityWorkspaceConflict constraint.

Namespace

Drupal\workspaces\Plugin\Validation\Constraint

Code

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

  /** @var \Drupal\Core\Entity\EntityInterface $entity */
  if (isset($entity) && !$entity
    ->isNew()) {
    $active_workspace = $this->workspaceManager
      ->getActiveWorkspace();

    // Get the latest revision of the entity in order to check if it's being
    // edited in a different workspace.
    $latest_revision = $this->workspaceManager
      ->executeOutsideWorkspace(function () use ($entity) {
      $storage = $this->entityTypeManager
        ->getStorage($entity
        ->getEntityTypeId());
      return $storage
        ->loadRevision($storage
        ->getLatestRevisionId($entity
        ->id()));
    });

    // If the latest revision of the entity is tracked in a workspace, it can
    // only be edited in that workspace or one of its descendants.
    if ($latest_revision_workspace = $latest_revision->workspace->entity) {
      $descendants_and_self = $this->workspaceRepository
        ->getDescendantsAndSelf($latest_revision_workspace
        ->id());
      if (!$active_workspace || !in_array($active_workspace
        ->id(), $descendants_and_self, TRUE)) {
        $this->context
          ->buildViolation($constraint->message)
          ->setParameter('%label', $latest_revision_workspace
          ->label())
          ->addViolation();
      }
    }
  }
}