|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/* |
| 6 | + * This file is part of the BazingaGeocoderBundle package. |
| 7 | + * For the full copyright and license information, please view the LICENSE |
| 8 | + * file that was distributed with this source code. |
| 9 | + * |
| 10 | + * @license MIT License |
| 11 | + */ |
| 12 | + |
| 13 | +namespace Bazinga\GeocoderBundle\Validator\Constraint; |
| 14 | + |
| 15 | +use Geocoder\Exception\Exception; |
| 16 | +use Geocoder\Provider\Provider; |
| 17 | +use Geocoder\Query\GeocodeQuery; |
| 18 | +use Symfony\Component\Validator\Constraint; |
| 19 | +use Symfony\Component\Validator\ConstraintValidator; |
| 20 | +use Symfony\Component\Validator\Exception\UnexpectedTypeException; |
| 21 | +use Symfony\Component\Validator\Exception\UnexpectedValueException; |
| 22 | + |
| 23 | +/** |
| 24 | + * @author Tomas Norkūnas <norkunas.tom@gmail.com> |
| 25 | + */ |
| 26 | +class AddressValidator extends ConstraintValidator |
| 27 | +{ |
| 28 | + protected $addressGeocoder; |
| 29 | + |
| 30 | + public function __construct(Provider $addressGeocoder) |
| 31 | + { |
| 32 | + $this->addressGeocoder = $addressGeocoder; |
| 33 | + } |
| 34 | + |
| 35 | + public function validate($value, Constraint $constraint) |
| 36 | + { |
| 37 | + if (!$constraint instanceof Address) { |
| 38 | + throw new UnexpectedTypeException($constraint, Address::class); |
| 39 | + } |
| 40 | + |
| 41 | + if (null === $value || '' === $value) { |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) { |
| 46 | + if (class_exists(UnexpectedValueException::class)) { |
| 47 | + throw new UnexpectedValueException($value, 'string'); |
| 48 | + } else { |
| 49 | + throw new UnexpectedTypeException($value, 'string'); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + $value = (string) $value; |
| 54 | + |
| 55 | + try { |
| 56 | + $collection = $this->addressGeocoder->geocodeQuery(GeocodeQuery::create($value)); |
| 57 | + |
| 58 | + if ($collection->isEmpty()) { |
| 59 | + $this->buildViolation($constraint, $value); |
| 60 | + } |
| 61 | + } catch (Exception $e) { |
| 62 | + $this->buildViolation($constraint, $value); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + private function buildViolation(Address $constraint, string $address) |
| 67 | + { |
| 68 | + $this->context->buildViolation($constraint->message) |
| 69 | + ->setParameter('{{ address }}', $this->formatValue($address)) |
| 70 | + ->setInvalidValue($address) |
| 71 | + ->setCode(Address::INVALID_ADDRESS_ERROR) |
| 72 | + ->addViolation(); |
| 73 | + } |
| 74 | +} |
0 commit comments