FieldValidationTest.php in Drupal 9
File
core/modules/field/tests/src/Kernel/FieldValidationTest.php
View source
<?php
namespace Drupal\Tests\field\Kernel;
class FieldValidationTest extends FieldKernelTestBase {
private $entityType;
private $bundle;
private $entity;
protected function setUp() : void {
parent::setUp();
$this->entityType = 'entity_test';
$this->bundle = 'entity_test';
$this
->createFieldWithStorage('', $this->entityType, $this->bundle);
$this->entity = \Drupal::entityTypeManager()
->getStorage($this->entityType)
->create([
'type' => $this->bundle,
]);
}
public function testCardinalityConstraint() {
$cardinality = $this->fieldTestData->field_storage
->getCardinality();
$entity = $this->entity;
for ($delta = 0; $delta < $cardinality + 1; $delta++) {
$entity->{$this->fieldTestData->field_name}[] = [
'value' => 1,
];
}
$violations = $entity->{$this->fieldTestData->field_name}
->validate();
$this
->assertCount(1, $violations);
$this
->assertEquals('', $violations[0]
->getPropertyPath());
$this
->assertEquals(t('%name: this field cannot hold more than @count values.', [
'%name' => $this->fieldTestData->field
->getLabel(),
'@count' => $cardinality,
]), $violations[0]
->getMessage());
}
public function testFieldConstraints() {
$cardinality = $this->fieldTestData->field_storage
->getCardinality();
$entity = $this->entity;
$this
->assertGreaterThan(1, $cardinality);
$expected_violations = [];
for ($delta = 0; $delta < $cardinality; $delta++) {
if ($delta == 1) {
$value = 1;
}
else {
$value = -1;
$expected_violations[$delta . '.value'][] = t('%name does not accept the value -1.', [
'%name' => $this->fieldTestData->field
->getLabel(),
]);
}
$entity->{$this->fieldTestData->field_name}[] = $value;
}
$violations = $entity->{$this->fieldTestData->field_name}
->validate();
$violations_by_path = [];
foreach ($violations as $violation) {
$violations_by_path[$violation
->getPropertyPath()][] = $violation
->getMessage();
}
$this
->assertEquals($expected_violations, $violations_by_path);
}
}