AddressValidator::buildViolation()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 7
cts 7
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
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 <[email protected]>
25
 */
26
class AddressValidator extends ConstraintValidator
27
{
28
    protected $addressGeocoder;
29
30 5
    public function __construct(Provider $addressGeocoder)
31
    {
32 5
        $this->addressGeocoder = $addressGeocoder;
33 5
    }
34
35 5
    public function validate($value, Constraint $constraint)
36
    {
37 5
        if (!$constraint instanceof Address) {
38
            throw new UnexpectedTypeException($constraint, Address::class);
39
        }
40
41 5
        if (null === $value || '' === $value) {
42 2
            return;
43
        }
44
45 3
        if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
46 1
            if (class_exists(UnexpectedValueException::class)) {
47 1
                throw new UnexpectedValueException($value, 'string');
48
            } else {
49
                throw new UnexpectedTypeException($value, 'string');
50
            }
51
        }
52
53 2
        $value = (string) $value;
54
55
        try {
56 2
            $collection = $this->addressGeocoder->geocodeQuery(GeocodeQuery::create($value));
57
58 2
            if ($collection->isEmpty()) {
59 2
                $this->buildViolation($constraint, $value);
60
            }
61
        } catch (Exception $e) {
62
            $this->buildViolation($constraint, $value);
63
        }
64 2
    }
65
66 1
    private function buildViolation(Address $constraint, string $address)
67
    {
68 1
        $this->context->buildViolation($constraint->message)
69 1
            ->setParameter('{{ address }}', $this->formatValue($address))
70 1
            ->setInvalidValue($address)
71 1
            ->setCode(Address::INVALID_ADDRESS_ERROR)
72 1
            ->addViolation();
73 1
    }
74
}
75