1
1
<?php
2
2
namespace Swango \HttpServer \Validator ;
3
3
class BackedEnum extends \Swango \HttpServer \Validator {
4
- public function __construct ($ cnkey , protected string $ enum_class ) {
4
+ public function __construct ($ cnkey , protected string $ enum_class, protected ? array $ valid_array = null ) {
5
5
parent ::__construct ($ cnkey );
6
6
}
7
7
public function getCnMsg (): string {
8
8
if (isset ($ this ->cnmsg )) {
9
9
return $ this ->cnmsg ;
10
10
}
11
- $ enum = [];
12
- foreach (($ this ->enum_class )::cases () as $ case )
13
- $ enum [] = $ case ->value ;
14
- $ ret = $ this ->cnkey . '必须为( ' . implode (', ' , $ enum ) . ')中的一项 ' ;
11
+ $ enums = [];
12
+ if (isset ($ this ->valid_array )) {
13
+ foreach ($ this ->valid_array as $ case )
14
+ $ enums [] = $ case ->value ;
15
+ } else {
16
+ foreach (($ this ->enum_class )::cases () as $ case )
17
+ $ enums [] = $ case ->value ;
18
+ }
19
+ $ ret = $ this ->cnkey . '必须为( ' . implode (', ' , $ enums ) . ')中的一项 ' ;
15
20
if (! $ this ->isOptional () || ! $ this ->couldBeNull ()) {
16
21
$ ret .= '且不可缺省 ' ;
17
22
}
@@ -25,5 +30,8 @@ protected function check(?string $key, &$value): void {
25
30
if (! isset ($ value )) {
26
31
throw new \ExceptionToResponse \InvalidParameterException ('Invalid ' . $ key , $ this ->getCnMsg ());
27
32
}
33
+ if (isset ($ this ->valid_array ) && ! in_array ($ value , $ this ->valid_array )) {
34
+ throw new \ExceptionToResponse \InvalidParameterException ('Invalid ' . $ key , $ this ->getCnMsg ());
35
+ }
28
36
}
29
37
}
0 commit comments