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 Symfony\Component\Validator\Constraints\Count; |
13
|
|
|
use Symfony\Component\Validator\Constraints\NotBlank; |
14
|
|
|
use Symfony\Component\Validator\Constraints\Regex; |
15
|
|
|
use Symfony\Component\Validator\ConstraintViolationListInterface; |
16
|
|
|
use Symfony\Component\Validator\Validation; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @Annotation |
20
|
|
|
*/ |
21
|
|
|
class FkConstraintValidator |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @param mixed $string |
25
|
|
|
*/ |
26
|
37 |
|
public function validate($string): ConstraintViolationListInterface |
27
|
|
|
{ |
28
|
37 |
|
if (($errors = $this->validateNotEmpty($string))->count()) { |
29
|
2 |
|
return $errors; |
30
|
|
|
} |
31
|
|
|
|
32
|
35 |
|
if (($errors = $this->validateCount($string))->count()) { |
33
|
|
|
return $errors; |
34
|
|
|
} |
35
|
|
|
|
36
|
35 |
|
return $this->validateRegex($string); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param mixed $string |
41
|
|
|
*/ |
42
|
37 |
|
private function validateNotEmpty($string): ConstraintViolationListInterface |
43
|
|
|
{ |
44
|
37 |
|
$validator = Validation::createValidator(); |
45
|
|
|
|
46
|
37 |
|
return $validator->validate($string, [ |
47
|
37 |
|
new NotBlank(), |
48
|
|
|
]); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param mixed $string |
53
|
|
|
*/ |
54
|
35 |
|
private function validateCount($string): ConstraintViolationListInterface |
55
|
|
|
{ |
56
|
35 |
|
$validator = Validation::createValidator(); |
57
|
|
|
|
58
|
35 |
|
$parts = \is_string($string) ? \explode(',', $string) : $string; |
59
|
|
|
|
60
|
35 |
|
return $validator->validate($parts, [ |
61
|
35 |
|
new Count([ |
62
|
35 |
|
'min' => 1, |
63
|
|
|
'max' => 3, |
64
|
|
|
'minMessage' => 'Allow table[,name[,id]]', |
65
|
|
|
'maxMessage' => 'Allow table[,name[,id]]', |
66
|
|
|
]), |
67
|
|
|
]); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @param mixed $string |
72
|
|
|
*/ |
73
|
35 |
|
private function validateRegex($string): ConstraintViolationListInterface |
74
|
|
|
{ |
75
|
35 |
|
$validator = Validation::createValidator(); |
76
|
|
|
|
77
|
35 |
|
$string = \is_array($string) ? \implode(',', $string) : $string; |
78
|
|
|
|
79
|
35 |
|
return $validator->validate($string, [ |
80
|
35 |
|
new Regex([ |
81
|
35 |
|
'pattern' => '/^[a-zA-Z][a-zA-Z0-9_,]*$/', |
82
|
|
|
'message' => 'Characters not allowed. Use: a-Z, 0-9 and underscore (except in begin)', |
83
|
|
|
]), |
84
|
|
|
]); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|