Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
17 / 17 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
Enum | |
100.00% |
17 / 17 |
|
100.00% |
3 / 3 |
10 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
execute | |
100.00% |
8 / 8 |
|
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\MongoDB\Validator\Attributes; |
10 | |
11 | use Attribute; |
12 | use Selen\Data\Enum as DataEnum; |
13 | use Selen\MongoDB\Validator\Model\ValidateResult; |
14 | use Selen\MongoDB\Validator\ValueValidateInterface; |
15 | |
16 | #[Attribute(Attribute::TARGET_PROPERTY)] |
17 | class Enum implements ValueValidateInterface |
18 | { |
19 | /** @var array<int,string|int|float|bool|null> */ |
20 | private $allowValues; |
21 | |
22 | public function __construct(string|int|float|bool|null ...$values) |
23 | { |
24 | $this->allowValues = $values; |
25 | } |
26 | |
27 | public function execute($value, ValidateResult $result): ValidateResult |
28 | { |
29 | if (DataEnum::validate($value, ...$this->allowValues)) { |
30 | return $result; |
31 | } |
32 | |
33 | $viewValues = []; |
34 | |
35 | foreach ($this->allowValues as $allowValue) { |
36 | $viewValues[] = $this->surround($allowValue); |
37 | } |
38 | |
39 | $format = 'Invalid value. expected value %s.'; |
40 | $mes = \sprintf($format, \implode(', ', $viewValues)); |
41 | return $result->setResult(false)->setMessage($mes); |
42 | } |
43 | |
44 | private function surround(string|float|int|bool|null $value): string |
45 | { |
46 | switch (true) { |
47 | case \is_string($value): |
48 | return \sprintf("'%s'", $value); |
49 | case \is_bool($value): |
50 | return $value ? 'true' : 'false'; |
51 | case \is_null($value): |
52 | return 'null'; |
53 | default: |
54 | // NOTE: float, intのときは抜ける |
55 | break; |
56 | } |
57 | return \sprintf('%s', $value); |
58 | } |
59 | } |