68 lines
2.2 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\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Templating\Entity\PersonRenderInterface;
use Chill\ThirdPartyBundle\Templating\Entity\ThirdPartyRender;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use function count;
use function in_array;
class ResourceDuplicateCheckValidator extends ConstraintValidator
{
private PersonRenderInterface $personRender;
private ThirdPartyRender $thirdpartyRender;
public function __construct(PersonRenderInterface $personRender, ThirdPartyRender $thirdPartyRender)
{
$this->personRender = $personRender;
$this->thirdpartyRender = $thirdPartyRender;
}
public function validate($resources, Constraint $constraint)
{
if (!$constraint instanceof ResourceDuplicateCheck) {
throw new UnexpectedTypeException($constraint, ParticipationOverlap::class);
}
if (!$resources instanceof Collection) {
throw new UnexpectedTypeException($resources, Collection::class);
}
if (0 === count($resources)) {
return;
}
$resourceList = [];
foreach ($resources as $resource) {
$id = ($resource->getResource() instanceof Person ? 'p' :
't') . $resource->getResource()->getId();
if (in_array($id, $resourceList, true)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ name }}', $resource->getResource() instanceof Person ? $this->personRender->renderString($resource->getResource(), []) :
$this->thirdpartyRender->renderString($resource->getResource(), []))
->addViolation();
}
$resourceList[] = $id;
}
}
}