EntityWorkspaceConflictConstraintValidator.php in Drupal 10
File
core/modules/workspaces/src/Plugin/Validation/Constraint/EntityWorkspaceConflictConstraintValidator.php
View source
<?php
namespace Drupal\workspaces\Plugin\Validation\Constraint;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\workspaces\WorkspaceAssociationInterface;
use Drupal\workspaces\WorkspaceManagerInterface;
use Drupal\workspaces\WorkspaceRepositoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class EntityWorkspaceConflictConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
protected $entityTypeManager;
protected $workspaceManager;
protected $workspaceAssociation;
protected $workspaceRepository;
public function __construct(EntityTypeManagerInterface $entity_type_manager, WorkspaceManagerInterface $workspace_manager, WorkspaceAssociationInterface $workspace_association, WorkspaceRepositoryInterface $workspace_repository) {
$this->entityTypeManager = $entity_type_manager;
$this->workspaceManager = $workspace_manager;
$this->workspaceAssociation = $workspace_association;
$this->workspaceRepository = $workspace_repository;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager'), $container
->get('workspaces.manager'), $container
->get('workspaces.association'), $container
->get('workspaces.repository'));
}
public function validate($entity, Constraint $constraint) {
if (isset($entity) && !$entity
->isNew()) {
$active_workspace = $this->workspaceManager
->getActiveWorkspace();
$latest_revision = $this->workspaceManager
->executeOutsideWorkspace(function () use ($entity) {
$storage = $this->entityTypeManager
->getStorage($entity
->getEntityTypeId());
return $storage
->loadRevision($storage
->getLatestRevisionId($entity
->id()));
});
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();
}
}
}
}
}