Skip to content

Commit

Permalink
update errors handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Vladyslav Yarysh committed May 1, 2024
1 parent 29b490a commit 018356b
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions Validator/Constraints/Entity/EntityExistsValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

namespace StfalconStudio\ApiBundle\Validator\Constraints\Entity;

use StfalconStudio\ApiBundle\Exception\LogicException;
use StfalconStudio\ApiBundle\Exception\Validator\UnexpectedConstraintException;
use StfalconStudio\ApiBundle\Traits\EntityManagerTrait;
use Symfony\Component\Validator\Constraint;
Expand All @@ -36,13 +37,21 @@ public function validate(mixed $value, Constraint|EntityExists $constraint): voi
throw new UnexpectedConstraintException($constraint, EntityExists::class);
}

if (!(\is_int($value) || \is_string($value))) {
return;
$entityClass = $constraint->class;

try {
$this->em->getClassMetadata($entityClass);
} catch (\Exception $exception) {
throw new LogicException(sprintf('Class %s is not an Entity', $entityClass));
}

$repository = $this->em->getRepository($constraint->class);

if (!$repository->findOneBy([$constraint->property => $value]) instanceof $constraint->class) {
if (!(\is_int($value) || \is_string($value) || $value instanceof \Stringable)) {
throw new LogicException(sprintf('Value expected to be int, string or implement %s to find cause of the problem', \Stringable::class));
}

$this->context
->buildViolation($constraint->message)
->setCode(EntityExists::ENTITY_DOES_NOT_EXIST)
Expand Down

0 comments on commit 018356b

Please sign in to comment.