Files
chill-bundles/src/Bundle/ChillPersonBundle/Validator/Constraints/Relationship/RelationshipNoDuplicateValidator.php

62 lines
2.0 KiB
PHP

<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\PersonBundle\Validator\Constraints\Relationship;
use Chill\PersonBundle\Entity\Relationships\Relationship;
use Chill\PersonBundle\Repository\Relationships\RelationshipRepository;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
class RelationshipNoDuplicateValidator extends ConstraintValidator
{
private RelationshipRepository $relationshipRepository;
public function __construct(RelationshipRepository $relationshipRepository)
{
$this->relationshipRepository = $relationshipRepository;
}
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof RelationshipNoDuplicate) {
throw new UnexpectedTypeException($constraint, RelationshipNoDuplicate::class);
}
if (!$value instanceof Relationship) {
throw new UnexpectedValueException($value, Relationship::class);
}
$fromPerson = $value->getFromPerson();
$toPerson = $value->getToPerson();
$relationType = $value->getRelation();
$relationships = $this->relationshipRepository->findBy([
'fromPerson' => [$fromPerson, $toPerson],
'toPerson' => [$fromPerson, $toPerson],
]);
foreach ($relationships as $r) {
if ($r->getRelation()->getId() !== $relationType->getId()
&& ($r->getFromPerson() === $fromPerson
|| $r->getFromPerson() === $toPerson
|| $r->getToPerson() === $fromPerson
|| $r->getToPerson() === $toPerson)
) {
$this->context->buildViolation($constraint->message)
->addViolation();
}
}
}
}