function RecursiveContextualValidatorTest::testRecursiveViolationPropagation

Same name and namespace in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/TypedData/RecursiveContextualValidatorTest.php \Drupal\KernelTests\Core\TypedData\RecursiveContextualValidatorTest::testRecursiveViolationPropagation()
  2. 8.9.x core/tests/Drupal/KernelTests/Core/TypedData/RecursiveContextualValidatorTest.php \Drupal\KernelTests\Core\TypedData\RecursiveContextualValidatorTest::testRecursiveViolationPropagation()
  3. 10 core/tests/Drupal/KernelTests/Core/TypedData/RecursiveContextualValidatorTest.php \Drupal\KernelTests\Core\TypedData\RecursiveContextualValidatorTest::testRecursiveViolationPropagation()

Tests recursive propagation of violations.

File

core/tests/Drupal/KernelTests/Core/TypedData/RecursiveContextualValidatorTest.php, line 50

Class

RecursiveContextualValidatorTest
@coversDefaultClass \Drupal\Core\TypedData\Validation\RecursiveContextualValidator[[api-linebreak]] @group Validation

Namespace

Drupal\KernelTests\Core\TypedData

Code

public function testRecursiveViolationPropagation() : void {
  // We create an entity reference field with a constraint which will
  // trigger the validation of the referenced entities. Then we add a
  // required field and populate it only on the parent entity, so that
  // the child entity fails the validation.
  $definitions['field_test'] = BaseFieldDefinition::create('entity_reference')->setLabel('Test reference')
    ->setSetting('target_type', 'entity_test')
    ->addConstraint('TestValidatedReferenceConstraint');
  $definitions['string_required'] = BaseFieldDefinition::create('string')->setLabel('Required string')
    ->setRequired(TRUE);
  $this->container
    ->get('state')
    ->set('entity_test.additional_base_field_definitions', $definitions);
  $this->installEntitySchema('entity_test');
  $child = EntityTest::create([
    'name' => 'test2',
    'user_id' => [
      'target_id' => 0,
    ],
  ]);
  $parent = EntityTest::create([
    'name' => 'test',
    'user_id' => [
      'target_id' => 0,
    ],
    'string_required' => 'some string',
    'field_test' => [
      'entity' => $child,
    ],
  ]);
  // The child entity should fail the validation and the violation should
  // propagate to the parent.
  $violations = $parent->validate();
  $this->assertCount(1, $violations);
  $this->assertEquals('field_test', $violations[0]->getPropertyPath());
  $this->assertEquals('Invalid referenced entity.', $violations[0]->getMessage());
}

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