Skip to content

Commit f7c3a13

Browse files
committed
support for BackedEnum
1 parent 566502e commit f7c3a13

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

src/Validator/BackedEnum.php

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,22 @@
11
<?php
22
namespace Swango\HttpServer\Validator;
33
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) {
55
parent::__construct($cnkey);
66
}
77
public function getCnMsg(): string {
88
if (isset($this->cnmsg)) {
99
return $this->cnmsg;
1010
}
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) . ')中的一项';
1520
if (! $this->isOptional() || ! $this->couldBeNull()) {
1621
$ret .= '且不可缺省';
1722
}
@@ -25,5 +30,8 @@ protected function check(?string $key, &$value): void {
2530
if (! isset($value)) {
2631
throw new \ExceptionToResponse\InvalidParameterException('Invalid ' . $key, $this->getCnMsg());
2732
}
33+
if (isset($this->valid_array) && ! in_array($value, $this->valid_array)) {
34+
throw new \ExceptionToResponse\InvalidParameterException('Invalid ' . $key, $this->getCnMsg());
35+
}
2836
}
2937
}

0 commit comments

Comments
 (0)