You are here

public function TaxonomyTermHierarchyConstraintValidator::validate in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/taxonomy/src/Plugin/Validation/Constraint/TaxonomyTermHierarchyConstraintValidator.php \Drupal\taxonomy\Plugin\Validation\Constraint\TaxonomyTermHierarchyConstraintValidator::validate()

File

core/modules/taxonomy/src/Plugin/Validation/Constraint/TaxonomyTermHierarchyConstraintValidator.php, line 46

Class

TaxonomyTermHierarchyConstraintValidator
Constraint validator for changing term parents in pending revisions.

Namespace

Drupal\taxonomy\Plugin\Validation\Constraint

Code

public function validate($entity, Constraint $constraint) {
  $term_storage = $this->entityTypeManager
    ->getStorage($entity
    ->getEntityTypeId());
  assert($term_storage instanceof TermStorageInterface);

  // Newly created entities should be able to specify a parent.
  if ($entity && $entity
    ->isNew()) {
    return;
  }
  $is_pending_revision = !$entity
    ->isDefaultRevision();
  $pending_term_ids = $term_storage
    ->getTermIdsWithPendingRevisions();
  $ancestors = $term_storage
    ->loadAllParents($entity
    ->id());
  $ancestor_is_pending_revision = (bool) array_intersect_key($ancestors, array_flip($pending_term_ids));
  $new_parents = array_column($entity->parent
    ->getValue(), 'target_id');
  $original_parents = array_keys($term_storage
    ->loadParents($entity
    ->id())) ?: [
    0,
  ];
  if (($is_pending_revision || $ancestor_is_pending_revision) && $new_parents != $original_parents) {
    $this->context
      ->buildViolation($constraint->message)
      ->atPath('parent')
      ->addViolation();
  }
  $original = $term_storage
    ->loadUnchanged($entity
    ->id());
  if (($is_pending_revision || $ancestor_is_pending_revision) && !$entity->weight
    ->equals($original->weight)) {
    $this->context
      ->buildViolation($constraint->message)
      ->atPath('weight')
      ->addViolation();
  }
}