EntityChangedConstraintValidator.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. namespace Drupal\Core\Entity\Plugin\Validation\Constraint;
  3. use Symfony\Component\Validator\Constraint;
  4. use Symfony\Component\Validator\ConstraintValidator;
  5. /**
  6. * Validates the EntityChanged constraint.
  7. */
  8. class EntityChangedConstraintValidator extends ConstraintValidator {
  9. /**
  10. * {@inheritdoc}
  11. */
  12. public function validate($entity, Constraint $constraint) {
  13. if (isset($entity)) {
  14. /** @var \Drupal\Core\Entity\EntityInterface $entity */
  15. if (!$entity->isNew()) {
  16. $saved_entity = \Drupal::entityTypeManager()->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id());
  17. // Ensure that all the entity translations are the same as or newer
  18. // than their current version in the storage in order to avoid
  19. // reverting other changes. In fact the entity object that is being
  20. // saved might contain an older entity translation when different
  21. // translations are being concurrently edited.
  22. if ($saved_entity) {
  23. $common_translation_languages = array_intersect_key($entity->getTranslationLanguages(), $saved_entity->getTranslationLanguages());
  24. foreach (array_keys($common_translation_languages) as $langcode) {
  25. // Merely comparing the latest changed timestamps across all
  26. // translations is not sufficient since other translations may have
  27. // been edited and saved in the meanwhile. Therefore, compare the
  28. // changed timestamps of each entity translation individually.
  29. if ($saved_entity->getTranslation($langcode)->getChangedTime() > $entity->getTranslation($langcode)->getChangedTime()) {
  30. $this->context->addViolation($constraint->message);
  31. break;
  32. }
  33. }
  34. }
  35. }
  36. }
  37. }
  38. }