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 11<?php
22namespace Swango \HttpServer \Validator ;
33class Enum extends \Swango \HttpServer \Validator {
4- private $ enum , $ all_string ;
4+ private array $ enum ;
5+ private bool $ all_string ;
56 public function __construct ($ cnkey , array $ enum ) {
67 parent ::__construct ($ cnkey );
78 $ this ->enum = $ enum ;
89 $ this ->all_string = true ;
9- foreach ($ enum as $ item )
10+ foreach ($ enum as $ item ) {
11+ if ($ item instanceof \BackedEnum) {
12+ $ item = $ item ->value ;
13+ }
1014 if (! is_string ($ item ) && ! is_numeric ($ item )) {
1115 $ this ->all_string = false ;
1216 break ;
1317 }
18+ }
1419 }
1520 public function getCnMsg (): string {
1621 if (isset ($ this ->cnmsg ))
You can’t perform that action at this time.
0 commit comments