Add ThirdPartyHasEmail validator

Introduce a new validator that ensures a third party has an email address, including the corresponding translation for error messaging and unit tests to verify its functionality.
This commit is contained in:
2024-10-03 17:14:42 +02:00
parent a563ba644e
commit da6589ba87
5 changed files with 146 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
/*
* 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.
*/
namespace Chill\ThirdPartyBundle\Validator;
use Symfony\Component\Validator\Constraint;
/**
* Add a constraint to check that the thirdparty has an email address.
*/
class ThirdPartyHasEmail extends Constraint
{
public string $message = 'thirdParty.thirdParty_has_no_email';
public string $code = 'f2da71f8-818c-11ef-9f6a-3ba3597ab60b';
/**
* @return array<string>|string
*/
public function getTargets(): array|string
{
return [self::PROPERTY_CONSTRAINT];
}
}

View File

@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
/*
* 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.
*/
namespace Chill\ThirdPartyBundle\Validator;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use Chill\ThirdPartyBundle\Templating\Entity\ThirdPartyRender;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
final class ThirdPartyHasEmailValidator extends ConstraintValidator
{
public function __construct(private readonly ThirdPartyRender $thirdPartyRender) {}
public function validate($value, Constraint $constraint): void
{
if (!$constraint instanceof ThirdPartyHasEmail) {
throw new UnexpectedTypeException($constraint, ThirdPartyHasEmail::class);
}
if (null === $value) {
return;
}
if (!$value instanceof ThirdParty) {
throw new UnexpectedTypeException($value, ThirdParty::class);
}
if (null === $value->getEmail() || '' === $value->getEmail()) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ thirdParty }}', $this->thirdPartyRender->renderString($value, []))
->setCode($constraint->code)
->addViolation();
}
}
}