Pol Dellaiera e1b3719746
Tests
2022-02-28 15:00:56 +01:00

79 lines
2.3 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\MainBundle\Validation\Validator;
use Chill\MainBundle\Phonenumber\PhoneNumberHelperInterface;
use LogicException;
use Psr\Log\LoggerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
final class ValidPhonenumber extends ConstraintValidator
{
private LoggerInterface $logger;
private PhoneNumberHelperInterface $phonenumberHelper;
public function __construct(
LoggerInterface $logger,
PhoneNumberHelperInterface $phonenumberHelper
) {
$this->phonenumberHelper = $phonenumberHelper;
$this->logger = $logger;
}
/**
* @param string $value
* @param \Chill\MainBundle\Validation\Constraint\PhonenumberConstraint $constraint
*/
public function validate($value, Constraint $constraint)
{
if (false === $this->phonenumberHelper->isPhonenumberValidationConfigured()) {
$this->logger->debug('[phonenumber] skipping validation due to not configured helper');
return;
}
if ('' === $value) {
return;
}
switch ($constraint->type) {
case 'landline':
$isValid = $this->phonenumberHelper->isValidPhonenumberLandOrVoip($value);
$message = $constraint->notLandlineMessage;
break;
case 'mobile':
$isValid = $this->phonenumberHelper->isValidPhonenumberMobile($value);
$message = $constraint->notMobileMessage;
break;
case 'any':
$isValid = $this->phonenumberHelper->isValidPhonenumberAny($value);
$message = $constraint->notValidMessage;
break;
default:
throw new LogicException(sprintf("This type '%s' is not implemented. "
. "Possible values are 'mobile', 'landline' or 'any'", $constraint->type));
}
if (false === $isValid) {
$this->context->addViolation($message, ['%phonenumber%' => $value]);
}
}
}