-
Notifications
You must be signed in to change notification settings - Fork 1
/
CoordinateConstraint.php
56 lines (44 loc) · 1.49 KB
/
CoordinateConstraint.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
declare(strict_types=1);
namespace Chubbyphp\Validation\Constraint;
use Chubbyphp\Validation\Error\Error;
use Chubbyphp\Validation\Error\ErrorInterface;
use Chubbyphp\Validation\ValidatorContextInterface;
use Chubbyphp\Validation\ValidatorInterface;
final class CoordinateConstraint implements ConstraintInterface
{
public const PATTERN = '/^([-+]?\d+(\.\d+)?)\s*,\s*([-+]?\d+(\.\d+)?)$/';
/**
* @param mixed $value
*
* @return array<ErrorInterface>
*/
public function validate(
string $path,
$value,
ValidatorContextInterface $context,
?ValidatorInterface $validator = null
) {
if (null === $value || '' === $value) {
return [];
}
if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
return [new Error(
$path,
'constraint.coordinate.invalidtype',
['type' => get_debug_type($value)]
)];
}
$value = (string) $value;
$matches = [];
if (!preg_match(self::PATTERN, $value, $matches)) {
return [new Error($path, 'constraint.coordinate.invalidformat', ['value' => $value])];
}
$lat = (float) $matches[1];
$lon = (float) $matches[3];
if ($lat < -90 || $lat > 90 || $lon < -180 || $lon > 180) {
return [new Error($path, 'constraint.coordinate.invalidvalue', ['value' => $value])];
}
return [];
}
}