You are here

public function MachineNameUniqueValidator::validate in Machine name 8

File

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

Class

MachineNameUniqueValidator
Validates that a field is unique for the given entity type.

Namespace

Drupal\machine_name\Plugin\Validation\Constraint

Code

public function validate($item, Constraint $constraint) {
  if ($item
    ->isEmpty()) {
    return NULL;
  }
  $entity = $item
    ->getEntity();
  $entity_id = $entity
    ->id();
  $entity_type = $entity
    ->getEntityType();
  $field_name = $item
    ->getFieldDefinition()
    ->getName();
  $properties = $item
    ->getProperties();

  // Query to see if existing entity with machine name exists.
  $query = \Drupal::entityQuery($entity_type
    ->id());
  foreach ($properties as $property) {
    $query
      ->condition($field_name . '.value', $property
      ->getValue());
    if (!empty($entity_id)) {
      $query
        ->condition($entity_type
        ->getKey('id'), $entity_id, '<>');
    }
    $result = $query
      ->execute();
    if (!empty($result)) {
      $this->context
        ->addViolation($constraint->message, array(
        '%value' => $property
          ->getValue(),
      ));
    }
  }
}