-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUniquePackageValidator.php
More file actions
47 lines (37 loc) · 1.43 KB
/
Copy pathUniquePackageValidator.php
File metadata and controls
47 lines (37 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
declare(strict_types=1);
namespace CodedMonkey\Dirigent\Validator;
use CodedMonkey\Dirigent\Doctrine\Entity\Package;
use CodedMonkey\Dirigent\Doctrine\Repository\PackageRepository;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
class UniquePackageValidator extends ConstraintValidator
{
public function __construct(
private readonly PackageRepository $packageRepository,
) {
}
public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof UniquePackage) {
throw new UnexpectedTypeException($constraint, UniquePackage::class);
}
if (null === $value || '' === $value) {
return;
}
if (!$value instanceof Package) {
throw new UnexpectedValueException($value, Package::class);
}
if (!$value->getName()) {
return;
}
$existingPackage = $this->packageRepository->findOneByName($value->getName());
if ($existingPackage && $existingPackage->getId() !== $value->getId()) {
$this->context->buildViolation('A package with the name ' . $value->getName() . ' already exists.')
->atPath('repositoryUrl')
->addViolation();
}
}
}