class ImmutablePropertiesConstraintValidator

Same name and namespace in other branches
  1. 11.x core/lib/Drupal/Core/Entity/Plugin/Validation/Constraint/ImmutablePropertiesConstraintValidator.php \Drupal\Core\Entity\Plugin\Validation\Constraint\ImmutablePropertiesConstraintValidator

Validates the ImmutableProperties constraint.

Hierarchy

Expanded class hierarchy of ImmutablePropertiesConstraintValidator

File

core/lib/Drupal/Core/Entity/Plugin/Validation/Constraint/ImmutablePropertiesConstraintValidator.php, line 20

Namespace

Drupal\Core\Entity\Plugin\Validation\Constraint
View source
class ImmutablePropertiesConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
  
  /**
   * Constructs an ImmutablePropertiesConstraintValidator object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager service.
   */
  public function __construct(protected EntityTypeManagerInterface $entityTypeManager) {
  }
  
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) : static {
    return new static($container->get('entity_type.manager'));
  }
  
  /**
   * {@inheritdoc}
   */
  public function validate(mixed $value, Constraint $constraint) {
    assert($constraint instanceof ImmutablePropertiesConstraint);
    if (!$value instanceof ConfigEntityInterface) {
      throw new UnexpectedValueException($value, ConfigEntityInterface::class);
    }
    // This validation is irrelevant on new entities.
    if ($value->isNew()) {
      return;
    }
    $id = $value->getOriginalId() ?: $value->id();
    if (empty($id)) {
      throw new LogicException('The entity does not have an ID.');
    }
    $original = $this->entityTypeManager
      ->getStorage($value->getEntityTypeId())
      ->loadUnchanged($id);
    if (empty($original)) {
      throw new RuntimeException('The original entity could not be loaded.');
    }
    foreach ($constraint->properties as $name) {
      // The property must be concretely defined in the class.
      if (!property_exists($value, $name)) {
        throw new LogicException("The entity does not have a '{$name}' property.");
      }
      if ($original->get($name) !== $value->get($name)) {
        $this->context
          ->addViolation($constraint->message, [
          '@name' => $name,
        ]);
      }
    }
  }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title
ImmutablePropertiesConstraintValidator::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create
ImmutablePropertiesConstraintValidator::validate public function
ImmutablePropertiesConstraintValidator::__construct public function Constructs an ImmutablePropertiesConstraintValidator object.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.