Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
95.00% |
19 / 20 |
|
66.67% |
2 / 3 |
CRAP | |
0.00% |
0 / 1 |
ArrayEnum | |
95.00% |
19 / 20 |
|
66.67% |
2 / 3 |
12 | |
0.00% |
0 / 1 |
__construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
execute | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
5 | |||
surround | |
87.50% |
7 / 8 |
|
0.00% |
0 / 1 |
6.07 |
1 | <?php |
2 | |
3 | /** |
4 | * @license MIT |
5 | * @author hazuki3417<hazuki3417@gmail.com> |
6 | * @copyright 2023 hazuki3417 all rights reserved. |
7 | */ |
8 | |
9 | namespace Selen\MongoDB\Validator\Attributes; |
10 | |
11 | use Attribute; |
12 | use Selen\Data\Enum; |
13 | use Selen\MongoDB\Validator\Model\ValidateResult; |
14 | use Selen\MongoDB\Validator\ValueValidateInterface; |
15 | |
16 | #[Attribute(Attribute::TARGET_PROPERTY)] |
17 | class ArrayEnum 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($values, ValidateResult $result): ValidateResult |
28 | { |
29 | $viewValues = []; |
30 | |
31 | foreach ($this->allowValues as $allowValue) { |
32 | $viewValues[] = $this->surround($allowValue); |
33 | } |
34 | |
35 | $format = 'Invalid type. expected array element type %s.'; |
36 | $mes = \sprintf($format, \implode(', ', $viewValues)); |
37 | |
38 | if (!\is_array($values)) { |
39 | return $result->setResult(false)->setMessage($mes); |
40 | } |
41 | |
42 | foreach ($values as $value) { |
43 | if (!Enum::validate($value, ...$this->allowValues)) { |
44 | return $result->setResult(false)->setMessage($mes); |
45 | } |
46 | } |
47 | |
48 | return $result->setResult(true); |
49 | } |
50 | |
51 | private function surround(string|float|int|bool|null $value): string |
52 | { |
53 | switch (true) { |
54 | case \is_string($value): |
55 | return \sprintf("'%s'", $value); |
56 | case \is_bool($value): |
57 | return $value ? 'true' : 'false'; |
58 | case \is_null($value): |
59 | return 'null'; |
60 | default: |
61 | // NOTE: float, intのときは抜ける |
62 | break; |
63 | } |
64 | return \sprintf('%s', $value); |
65 | } |
66 | } |