State constraint is not validated on new entities

Created on 23 October 2023, about 1 year ago
Updated 25 June 2024, 5 months ago

Problem/Motivation

The logic in StateConstraintValidator::validate() ignores invalid states on new entities.

This means it's possible to create a new entity with an invalid state, run $entity->validate() and it will not add a violation, which indicates to Drupal that the entity is valid, even though it has an invalid state.

Relevant code:

/**
 * Validates the State constraint.
 *
 * @see \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface::isValid()
 */
class StateConstraintValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($value, Constraint $constraint) {
    if (!$value->getEntity()->isNew() && !$value->isValid()) {
      $this->context->addViolation($constraint->message, ['@state' => $value->value]);
    }
  }

}

https://git.drupalcode.org/project/state_machine/-/blob/5516b0ae84a439e2...

Steps to reproduce

We discovered this in farmOS with our Migrate API based CSV importers. This can be reproduced with any migration that creates new entities with validate: true in the destination config.

It can also be reproduced in PHP by creating any entity with an invalid state and running $entity->validate(). There will be no violations.

Proposed resolution

I'm not sure why the if statement in StateConstraintValidator includes !$value->getEntity()->isNew() This means that it will never check validity on new entities.

This code traces back to the commit that originally introduced the StateConstraintValidator class by @bojanz ~7 years ago, so I wonder if it was a mistake that went unnoticed? There doesn't appear to be any comment explaining why "new" entities are excluded.

https://git.drupalcode.org/project/state_machine/-/commit/73cfdd9dde4fa9...

I will open a MR that removes this condition as a first step, and we can see if it causes any tests to fail.

Remaining tasks

- Create MR that removes the isNew() condition.
- See if tests fail.
- ...

User interface changes

None.

API changes

None.

Data model changes

None.

🐛 Bug report
Status

Fixed

Version

1.0

Component

Code

Created by

🇺🇸United States m.stenta

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024