You are here

public function FieldListUniqueValuesValidator::validate in Helper 8

1 call to FieldListUniqueValuesValidator::validate()
EntityFieldUniqueValuesValidator::validate in src/Plugin/Validation/Constraint/EntityFieldUniqueValuesValidator.php
Checks if the passed value is valid.
1 method overrides FieldListUniqueValuesValidator::validate()
EntityFieldUniqueValuesValidator::validate in src/Plugin/Validation/Constraint/EntityFieldUniqueValuesValidator.php
Checks if the passed value is valid.

File

src/Plugin/Validation/Constraint/FieldListUniqueValuesValidator.php, line 17

Class

FieldListUniqueValuesValidator
Validates duplicate field values.

Namespace

Drupal\helper\Plugin\Validation\Constraint

Code

public function validate($value, Constraint $constraint) {

  /** @var \Drupal\Core\Field\FieldItemListInterface $value */

  /** @var \Drupal\helper\Plugin\Validation\Constraint\FieldListUniqueValues $constraint */

  // If the field is empty or doesn't have more than one value, there is
  // nothing to validate.
  if (!isset($value) || count($value) <= 1) {
    return;
  }
  if ($duplicates = Field::getDuplicateValues($value, $constraint->property)) {
    if ($constraint->show_values) {
      $this->context
        ->addViolation($constraint->messageWithValues, [
        '%field_name' => $value
          ->getFieldDefinition()
          ->getLabel(),
        '@values' => implode(', ', $duplicates),
      ]);
    }
    else {
      $this->context
        ->addViolation($constraint->message, [
        '%field_name' => $value
          ->getFieldDefinition()
          ->getLabel(),
      ]);
    }
  }
}