Skip to content

Commit 566502e

Browse files
committed
support for BackedEnum
1 parent 3a87c75 commit 566502e

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

src/Validator/BackedEnum.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}

src/Validator/Enum.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,21 @@
11
<?php
22
namespace Swango\HttpServer\Validator;
33
class 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))

0 commit comments

Comments
 (0)