89 lines
2.4 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);
/**
* 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\MainBundle\Validation\Validator;
use Chill\MainBundle\Phonenumber\PhonenumberHelper;
use LogicException;
use Psr\Log\LoggerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ValidPhonenumber extends ConstraintValidator
{
protected $logger;
/**
* @var PhonenumberHelper
*/
protected $phonenumberHelper;
public function __construct(
LoggerInterface $logger,
PhonenumberHelper $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 (empty($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]);
}
}
}