function NoFieldItemsExistWithHigherCardinalityValidator::validate
File
-
core/
modules/ field/ src/ Plugin/ Validation/ Constraint/ NoFieldItemsExistWithHigherCardinalityValidator.php, line 55
Class
- NoFieldItemsExistWithHigherCardinalityValidator
- Validates the NoFieldItemsExistWithHigherCardinality constraint.
Namespace
Drupal\field\Plugin\Validation\ConstraintCode
public function validate(mixed $value, SymfonyConstraint $constraint) : void {
assert($constraint instanceof NoFieldItemsExistWithHigherCardinality);
// Cardinality should be an int, but could be passed differently.
$cardinality = (int) $value;
if ($cardinality === FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
return;
}
$object = $this->context
->getObject();
assert($object instanceof TypedDataInterface);
$entity_type = TypeResolver::resolveExpression($constraint->entityType, $object);
$field_name = TypeResolver::resolveExpression($constraint->fieldName, $object);
// We cannot check this constraint if the field storage does not exist.
$fieldStorageConfig = $this->entityTypeManager
->getStorage('field_storage_config')
->load($entity_type . '.' . $field_name);
if ($fieldStorageConfig === NULL) {
return;
}
if ($fieldStorageConfig->hasCustomStorage()) {
// If the field storage has custom storage, we cannot check this
// constraint.
return;
}
$max_delta_alias = 'max_delta';
$query = $this->entityTypeManager
->getStorage($entity_type)
->getAggregateQuery()
->aggregate($field_name . '.%delta', 'MAX', NULL, $max_delta_alias)
->accessCheck(FALSE);
$result = $query->execute();
$max_delta = 0;
if (is_array($result) && !empty($result)) {
if ($result[0][$max_delta_alias] !== NULL) {
// Delta starts at 0, so we need to add 1 to get the count of
// existing values.
$max_delta = (int) $result[0][$max_delta_alias] + 1;
}
}
if ($max_delta > $cardinality) {
$this->context
->addViolation($constraint->message, [
'@entity_type' => $entity_type,
'@field_name' => $field_name,
'@max_delta' => $max_delta,
'@cardinality' => $cardinality,
]);
}
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.