23
23
*/
24
24
class MacAddressValidator extends ConstraintValidator
25
25
{
26
+ /**
27
+ * Checks whether an MAC address is valid.
28
+ *
29
+ * @internal
30
+ */
31
+ public static function checkMac (string $ mac , mixed $ version ): bool
32
+ {
33
+ if (!filter_var ($ mac , \FILTER_VALIDATE_MAC )) {
34
+ return false ;
35
+ }
36
+
37
+ return match ($ version ) {
38
+ MacAddress::PUBLIC => !self ::isPrivate ($ mac ),
39
+ MacAddress::PRIVATE => self ::isPrivate ($ mac ),
40
+ default => true ,
41
+ };
42
+ }
43
+
44
+ /**
45
+ * Checks whether an MAC address is private.
46
+ *
47
+ * @internal
48
+ */
49
+ public static function isPrivate (string $ mac ): bool
50
+ {
51
+ return match (substr (strtolower ($ mac ), 1 , 1 )) {
52
+ '2 ' , '6 ' , 'a ' , 'e ' => true ,
53
+ default => false ,
54
+ };
55
+ }
56
+
26
57
public function validate (mixed $ value , Constraint $ constraint ): void
27
58
{
28
59
if (!$ constraint instanceof MacAddress) {
@@ -37,13 +68,13 @@ public function validate(mixed $value, Constraint $constraint): void
37
68
throw new UnexpectedValueException ($ value , 'string ' );
38
69
}
39
70
40
- $ value = (string ) $ value ;
71
+ $ value = (string )$ value ;
41
72
42
73
if (null !== $ constraint ->normalizer ) {
43
74
$ value = ($ constraint ->normalizer )($ value );
44
75
}
45
76
46
- if (!filter_var ($ value , \ FILTER_VALIDATE_MAC )) {
77
+ if (!self :: checkMac ($ value , $ constraint -> version )) {
47
78
$ this ->context ->buildViolation ($ constraint ->message )
48
79
->setParameter ('{{ value }} ' , $ this ->formatValue ($ value ))
49
80
->setCode (MacAddress::INVALID_MAC_ERROR )
0 commit comments