File tree Expand file tree Collapse file tree 2 files changed +36
-2
lines changed Expand file tree Collapse file tree 2 files changed +36
-2
lines changed Original file line number Diff line number Diff line change
1
+ <?php
2
+ namespace Swango \HttpServer \Validator ;
3
+ class BackedEnum extends \Swango \HttpServer \Validator {
4
+ public function __construct ($ cnkey , protected string $ enum_class ) {
5
+ parent ::__construct ($ cnkey );
6
+ }
7
+ public function getCnMsg (): string {
8
+ if (isset ($ this ->cnmsg )) {
9
+ return $ this ->cnmsg ;
10
+ }
11
+ $ enum = [];
12
+ foreach (($ this ->enum_class )::cases () as $ case )
13
+ $ enum [] = $ case ->value ;
14
+ $ ret = $ this ->cnkey . '必须为( ' . implode (', ' , $ enum ) . ')中的一项 ' ;
15
+ if (! $ this ->isOptional () || ! $ this ->couldBeNull ()) {
16
+ $ ret .= '且不可缺省 ' ;
17
+ }
18
+ return $ ret ;
19
+ }
20
+ protected function check (?string $ key , &$ value ): void {
21
+ if (is_array ($ value ) || is_object ($ value )) {
22
+ throw new \ExceptionToResponse \InvalidParameterException ('Invalid ' . $ key , $ this ->getCnMsg ());
23
+ }
24
+ $ value = ($ this ->enum_class )::tryFrom ($ value );
25
+ if (! isset ($ value )) {
26
+ throw new \ExceptionToResponse \InvalidParameterException ('Invalid ' . $ key , $ this ->getCnMsg ());
27
+ }
28
+ }
29
+ }
Original file line number Diff line number Diff line change 1
1
<?php
2
2
namespace Swango \HttpServer \Validator ;
3
3
class Enum extends \Swango \HttpServer \Validator {
4
- private $ enum , $ all_string ;
4
+ private array $ enum ;
5
+ private bool $ all_string ;
5
6
public function __construct ($ cnkey , array $ enum ) {
6
7
parent ::__construct ($ cnkey );
7
8
$ this ->enum = $ enum ;
8
9
$ this ->all_string = true ;
9
- foreach ($ enum as $ item )
10
+ foreach ($ enum as $ item ) {
11
+ if ($ item instanceof \BackedEnum) {
12
+ $ item = $ item ->value ;
13
+ }
10
14
if (! is_string ($ item ) && ! is_numeric ($ item )) {
11
15
$ this ->all_string = false ;
12
16
break ;
13
17
}
18
+ }
14
19
}
15
20
public function getCnMsg (): string {
16
21
if (isset ($ this ->cnmsg ))
You can’t perform that action at this time.
0 commit comments