You are here

public function EntityUntranslatableFieldsConstraintValidator::validate in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Entity/Plugin/Validation/Constraint/EntityUntranslatableFieldsConstraintValidator.php \Drupal\Core\Entity\Plugin\Validation\Constraint\EntityUntranslatableFieldsConstraintValidator::validate()
  2. 10 core/lib/Drupal/Core/Entity/Plugin/Validation/Constraint/EntityUntranslatableFieldsConstraintValidator.php \Drupal\Core\Entity\Plugin\Validation\Constraint\EntityUntranslatableFieldsConstraintValidator::validate()

File

core/lib/Drupal/Core/Entity/Plugin/Validation/Constraint/EntityUntranslatableFieldsConstraintValidator.php, line 49

Class

EntityUntranslatableFieldsConstraintValidator
Validates the EntityChanged constraint.

Namespace

Drupal\Core\Entity\Plugin\Validation\Constraint

Code

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

  /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */

  /** @var \Drupal\Core\Entity\Plugin\Validation\Constraint\EntityUntranslatableFieldsConstraint $constraint */

  // Untranslatable field restrictions apply only to revisions of multilingual
  // entities.
  if ($entity
    ->isNew() || !$entity
    ->isTranslatable() || !$entity
    ->getEntityType()
    ->isRevisionable()) {
    return;
  }
  if ($entity
    ->isDefaultRevision() && !$entity
    ->isDefaultTranslationAffectedOnly()) {
    return;
  }

  // To avoid unintentional reverts and data losses, we forbid changes to
  // untranslatable fields in pending revisions for multilingual entities. The
  // only case where changes in pending revisions are acceptable is when
  // untranslatable fields affect only the default translation, in which case
  // a pending revision contains only one affected translation. Even in this
  // case, multiple translations would be affected in a single revision, if we
  // allowed changes to untranslatable fields while editing non-default
  // translations, so that is forbidden too. For the same reason, when changes
  // to untranslatable fields affect all translations, we can only allow them
  // in default revisions.
  if ($this
    ->hasUntranslatableFieldsChanges($entity)) {
    if ($entity
      ->isDefaultTranslationAffectedOnly()) {
      foreach ($entity
        ->getTranslationLanguages(FALSE) as $langcode => $language) {
        if ($entity
          ->getTranslation($langcode)
          ->hasTranslationChanges()) {
          $this->context
            ->addViolation($constraint->defaultTranslationMessage);
          break;
        }
      }
    }
    else {
      $this->context
        ->addViolation($constraint->defaultRevisionMessage);
    }
  }
}