Here is how you can inject dependencies in ConstraintValidator class. You can read full article about validators and constraints here.
https://drupaljournal.com/article/drupal-9/entity-field-validators-and-constraints-drupal
<?php
namespace Drupal\askhub_base\Plugin\Validation\Constraint;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Drupal\Core\Entity\EntityTypeManagerInterface;
/**
* Validates the UniqueId constraint.
*/
class UniqueIdConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Creates a new UniqueIdConstraintValidator instance.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager')
);
}
/**
* {@inheritdoc}
*/
public function validate($items, Constraint $constraint) {
foreach ($items as $item) {
// Next check if the value is unique.
if (!$this->isUnique($item->value, $items)) {
$this->context->addViolation($constraint->notUnique, ['%value' => $item->value]);
}
}
}
/**
* Is unique?
*
* @param string $value
* Field value.
* @param \Drupal\Core\Field\FieldItemList $items
* Items list.
*/
private function isUnique($value, $items) {
$count = 0;
try {
$field_name = $items->getFieldDefinition()->getName();
$entity = $items->getEntity();
$entity_type_id = $entity->getEntityTypeId();
$bundle = $entity->bundle();
// Query.
$count = $this->entityTypeManager->getStorage($entity_type_id)
->getQuery()
->condition('type', $bundle)
->condition($field_name, $value)
->count()->execute();
}
catch (\Exception $e) {
// Log error.
}
return !(bool) $count;
}
}