vendor/shopware/core/Framework/DataAbstractionLayer/Validation/EntityExistsValidator.php line 44

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Framework\DataAbstractionLayer\Validation;
  3. use Shopware\Core\Framework\DataAbstractionLayer\DefinitionInstanceRegistry;
  4. use Shopware\Core\Framework\DataAbstractionLayer\Search\EntitySearcherInterface;
  5. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  6. use Shopware\Core\Framework\Log\Package;
  7. use Symfony\Component\Validator\Constraint;
  8. use Symfony\Component\Validator\ConstraintValidator;
  9. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  10. #[Package('core')]
  11. class EntityExistsValidator extends ConstraintValidator
  12. {
  13.     /**
  14.      * @internal
  15.      */
  16.     public function __construct(
  17.         private readonly DefinitionInstanceRegistry $definitionRegistry,
  18.         private readonly EntitySearcherInterface $entitySearcher
  19.     ) {
  20.     }
  21.     public function validate(mixed $valueConstraint $constraint): void
  22.     {
  23.         if (!$constraint instanceof EntityExists) {
  24.             throw new UnexpectedTypeException($constraintEntityExists::class);
  25.         }
  26.         if ($value === null || $value === '') {
  27.             return;
  28.         }
  29.         $definition $this->definitionRegistry->getByEntityName($constraint->getEntity());
  30.         $criteria = clone $constraint->getCriteria();
  31.         $criteria->addFilter(new EqualsFilter($constraint->getPrimaryProperty(), $value));
  32.         // Only one entity is enough to determine existence.
  33.         // As the property can be set in the constraint, the search above does not necessarily return just one entity.
  34.         $criteria->setLimit(1);
  35.         $result $this->entitySearcher->search($definition$criteria$constraint->getContext());
  36.         if ($result->getTotal() > 0) {
  37.             return;
  38.         }
  39.         $this->context->buildViolation($constraint->message)
  40.             ->setParameter('{{ primaryProperty }}'$constraint->getPrimaryProperty())
  41.             ->setParameter('{{ id }}'$this->formatValue($value))
  42.             ->setParameter('{{ entity }}'$this->formatValue($constraint->getEntity()))
  43.             ->setCode(EntityExists::ENTITY_DOES_NOT_EXISTS)
  44.             ->addViolation();
  45.     }
  46. }