Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
15 / 15 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
Enum | |
100.00% |
15 / 15 |
|
100.00% |
3 / 3 |
10 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
execute | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 | |||
surround | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
6 |
1 | <?php |
2 | |
3 | /** |
4 | * @license MIT |
5 | * @author hazuki3417<hazuki3417@gmail.com> |
6 | * @copyright 2022 hazuki3417 all rights reserved. |
7 | */ |
8 | |
9 | namespace Selen\Schema\Validate\Values; |
10 | |
11 | use Selen\Schema\Validate\Model\ValidateResult; |
12 | use Selen\Schema\Validate\ValueValidateInterface; |
13 | |
14 | class Enum implements ValueValidateInterface |
15 | { |
16 | /** @var string */ |
17 | protected $messageFormat = 'Invalid value. expected value %s.'; |
18 | |
19 | /** @var array<mixed,string|float|int|bool|null> */ |
20 | private $allowValues; |
21 | |
22 | public function __construct(string|float|int|bool|null ...$values) |
23 | { |
24 | $this->allowValues = $values; |
25 | } |
26 | |
27 | public function execute($value, ValidateResult $result): ValidateResult |
28 | { |
29 | if (\in_array($value, $this->allowValues, true)) { |
30 | return $result; |
31 | } |
32 | |
33 | foreach ($this->allowValues as $index => $allowValue) { |
34 | $this->allowValues[$index] = $this->surround($allowValue); |
35 | } |
36 | |
37 | $mes = \sprintf($this->messageFormat, \implode(', ', $this->allowValues)); |
38 | return $result->setResult(false)->setMessage($mes); |
39 | } |
40 | |
41 | private function surround(string|float|int|bool|null $value): string |
42 | { |
43 | switch (true) { |
44 | case \is_string($value): |
45 | return \sprintf("'%s'", $value); |
46 | case \is_bool($value): |
47 | return $value ? 'true' : 'false'; |
48 | case \is_null($value): |
49 | return 'null'; |
50 | default: |
51 | // NOTE: float, intのときは抜ける |
52 | break; |
53 | } |
54 | return \sprintf('%s', $value); |
55 | } |
56 | } |