Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
12 / 12 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
DateTimeFormat | |
100.00% |
12 / 12 |
|
100.00% |
2 / 2 |
7 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
execute | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
6 |
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\Schema\Validate\Values; |
10 | |
11 | use DateTime; |
12 | use Selen\Schema\Validate\Model\ValidateResult; |
13 | use Selen\Schema\Validate\ValueValidateInterface; |
14 | |
15 | class DateTimeFormat implements ValueValidateInterface |
16 | { |
17 | /** @var string */ |
18 | private $format; |
19 | |
20 | /** @var bool 空文字の許容ステータスを保持します(true: 許容する, false: 許容しない) */ |
21 | private bool $allowEmpty; |
22 | |
23 | /** |
24 | * @param string $format 日付フォーマットを指定します |
25 | * @param bool $allowEmpty 空文字を許容するか指定します。(true: 許容する, false: 許容しない) |
26 | */ |
27 | public function __construct(string $format, bool $allowEmpty = false) |
28 | { |
29 | $this->format = $format; |
30 | |
31 | $this->allowEmpty = $allowEmpty; |
32 | } |
33 | |
34 | public function execute($value, ValidateResult $result): ValidateResult |
35 | { |
36 | if (!\is_string($value)) { |
37 | $mes = 'Skip validation. Executed only when the value is of string type.'; |
38 | return $result->setResult(true)->setMessage($mes); |
39 | } |
40 | |
41 | if ($this->allowEmpty && $value === '') { |
42 | return $result->setResult(true); |
43 | } |
44 | |
45 | $dateTime = DateTime::createFromFormat($this->format, $value); |
46 | |
47 | if ($dateTime === false || $dateTime->format($this->format) !== $value) { |
48 | $mes = \sprintf('Invalid value. Expected value format %s.', $this->format); |
49 | return $result->setResult(false)->setMessage($mes); |
50 | } |
51 | |
52 | return $result->setResult(true); |
53 | } |
54 | } |