1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
/* |
3
|
|
|
* This file is part of FlexPHP. |
4
|
|
|
* |
5
|
|
|
* (c) Freddie Gar <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
namespace FlexPHP\Schema\Validators\Constraints; |
11
|
|
|
|
12
|
|
|
use FlexPHP\Schema\Constants\Format; |
13
|
|
|
use FlexPHP\Schema\Constants\Operator; |
14
|
|
|
use Symfony\Component\Validator\Constraints\Choice; |
15
|
|
|
use Symfony\Component\Validator\Constraints\NotBlank; |
16
|
|
|
use Symfony\Component\Validator\ConstraintViolationListInterface; |
17
|
|
|
use Symfony\Component\Validator\Validation; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @Annotation |
21
|
|
|
*/ |
22
|
|
|
class FormatConstraintValidator |
23
|
|
|
{ |
24
|
|
|
private const FORMATS = [ |
25
|
|
|
Format::MONEY, |
26
|
|
|
Format::TIMEAGO, |
27
|
|
|
Format::DATETIME, |
28
|
|
|
]; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param mixed $string |
32
|
|
|
*/ |
33
|
|
|
public function validate($string): ConstraintViolationListInterface |
34
|
|
|
{ |
35
|
|
|
if (($errors = $this->validateNotEmpty($string))->count()) { |
36
|
|
|
return $errors; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
return $this->validateValue($string); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param mixed $string |
44
|
|
|
*/ |
45
|
|
|
private function validateNotEmpty($string): ConstraintViolationListInterface |
46
|
|
|
{ |
47
|
|
|
$validator = Validation::createValidator(); |
48
|
|
|
|
49
|
|
|
return $validator->validate($string, [ |
50
|
|
|
new NotBlank(), |
51
|
|
|
]); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
private function validateValue(string $string): ConstraintViolationListInterface |
55
|
|
|
{ |
56
|
|
|
$validator = Validation::createValidator(); |
57
|
|
|
|
58
|
|
|
return $validator->validate($string, [ |
59
|
|
|
new Choice([ |
60
|
|
|
'choices' => self::FORMATS, |
61
|
|
|
'message' => 'Allowed values are: ' . \implode(',', self::FORMATS), |
62
|
|
|
]), |
63
|
|
|
]); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|