Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
19 / 19 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| DateTimeRange | |
100.00% |
19 / 19 |
|
100.00% |
3 / 3 |
5 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
| createRandom | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
2 | |||
| validateState | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | namespace Apie\DateValueObjects\Ranges; |
| 3 | |
| 4 | use Apie\Core\Attributes\Description; |
| 5 | use Apie\Core\Attributes\FakeMethod; |
| 6 | use Apie\Core\Exceptions\RangeMismatchException; |
| 7 | use Apie\Core\ValueObjects\CompositeValueObject; |
| 8 | use Apie\Core\ValueObjects\Interfaces\ValueObjectInterface; |
| 9 | use Apie\DateValueObjects\DateWithTimezone; |
| 10 | use Apie\Serializer\Exceptions\ValidationException; |
| 11 | use DateTime; |
| 12 | use Faker\Generator; |
| 13 | |
| 14 | #[FakeMethod("createRandom")] |
| 15 | #[Description("Represent a range between two Dates. The start date is always lower than the end date")] |
| 16 | final class DateTimeRange implements ValueObjectInterface |
| 17 | { |
| 18 | use CompositeValueObject; |
| 19 | |
| 20 | private DateWithTimezone $start; |
| 21 | private DateWithTimezone $end; |
| 22 | |
| 23 | public function __construct(DateWithTimezone $start, DateWithTimezone $end) |
| 24 | { |
| 25 | $this->start = $start; |
| 26 | $this->end = $end; |
| 27 | $this->validateState(); |
| 28 | } |
| 29 | |
| 30 | public static function createRandom(Generator $faker): self |
| 31 | { |
| 32 | $time1 = $faker->unixTime(); |
| 33 | $time2 = $faker->unixTime(); |
| 34 | if ($time1 > $time2) { |
| 35 | list($time2, $time1) = [$time1, $time2]; |
| 36 | } |
| 37 | $firstDate = new DateTime('@' . $time1); |
| 38 | $secondDate = new DateTime('@' . $time1); |
| 39 | |
| 40 | return new self( |
| 41 | DateWithTimezone::createFromDateTimeObject($firstDate), |
| 42 | DateWithTimezone::createFromDateTimeObject($secondDate), |
| 43 | ); |
| 44 | } |
| 45 | |
| 46 | private function validateState(): void |
| 47 | { |
| 48 | if ($this->start->toDate() > $this->end->toDate()) { |
| 49 | throw ValidationException::createFromArray( |
| 50 | [ |
| 51 | 'start' => new RangeMismatchException($this->start->toDate(), $this->end->toDate()) |
| 52 | ] |
| 53 | ); |
| 54 | } |
| 55 | } |
| 56 | } |