Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
| IsoDate | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
5 | |
100.00% |
1 / 1 |
| parse | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
5 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace App\Shared\Domain\ValueObject; |
| 6 | |
| 7 | use DateTimeImmutable; |
| 8 | use InvalidArgumentException; |
| 9 | |
| 10 | /** |
| 11 | * Strict ISO-8601 calendar-date parsing (Y-m-d), normalised to midnight. Shared |
| 12 | * by every value object/use case that accepts a date string so the "reject a |
| 13 | * malformed/non-ISO date" rule lives in one place. |
| 14 | */ |
| 15 | final class IsoDate |
| 16 | { |
| 17 | public static function parse(string $date): DateTimeImmutable |
| 18 | { |
| 19 | $parsed = DateTimeImmutable::createFromFormat('!Y-m-d', $date); |
| 20 | $errors = DateTimeImmutable::getLastErrors(); |
| 21 | |
| 22 | if ($parsed === false || ($errors !== false && ($errors['error_count'] > 0 || $errors['warning_count'] > 0))) { |
| 23 | throw new InvalidArgumentException(sprintf('Invalid date <%s>, expected format Y-m-d.', $date)); |
| 24 | } |
| 25 | |
| 26 | return $parsed; |
| 27 | } |
| 28 | } |