2020
2121/**
2222 * @psalm-import-type DateIntervalFormat from DateInterval
23- * @extends Type<int|Duration>
23+ * @psalm-import-type DateIntervalValue from DateInterval
24+ * @extends Type<int|Duration, DateIntervalValue>
2425 */
2526class DateIntervalType extends Type implements DetectableTypeInterface, RuleFactoryInterface
2627{
@@ -53,10 +54,6 @@ public static function makeRule(\ReflectionProperty $property): ?MarshallingRule
5354
5455 public function serialize ($ value ): int |Duration
5556 {
56- if ($ this ->format === DateInterval::FORMAT_NANOSECONDS ) {
57- return (int ) (DateInterval::parse ($ value , $ this ->format )->totalMicroseconds * 1000 );
58- }
59-
6057 if ($ this ->format === Duration::class) {
6158 return match (true ) {
6259 $ value instanceof \DateInterval => DateInterval::toDuration ($ value ),
@@ -69,8 +66,27 @@ public function serialize($value): int|Duration
6966 };
7067 }
7168
72- $ method = 'total ' . \ucfirst ($ this ->format );
73- return (int ) (DateInterval::parse ($ value , $ this ->format )->$ method );
69+ $ interval = DateInterval::parse ($ value , $ this ->format );
70+
71+ return (int ) match ($ this ->format ) {
72+ DateInterval::FORMAT_YEARS => $ interval ->totalYears ,
73+ DateInterval::FORMAT_MONTHS => $ interval ->totalMonths ,
74+ DateInterval::FORMAT_WEEKS => $ interval ->totalWeeks ,
75+ DateInterval::FORMAT_DAYS => $ interval ->totalDays ,
76+ DateInterval::FORMAT_HOURS => $ interval ->totalHours ,
77+ DateInterval::FORMAT_MINUTES => $ interval ->totalMinutes ,
78+ DateInterval::FORMAT_SECONDS => $ interval ->totalSeconds ,
79+ DateInterval::FORMAT_MILLISECONDS => $ interval ->totalMilliseconds ,
80+ DateInterval::FORMAT_MICROSECONDS => $ interval ->totalMicroseconds ,
81+ DateInterval::FORMAT_NANOSECONDS => (int ) \round ($ interval ->totalMicroseconds * 1000 ),
82+ default => throw new \InvalidArgumentException (
83+ \sprintf (
84+ 'Unsupported format: "%s". See %s for available formats. ' ,
85+ $ this ->format ,
86+ DateInterval::class,
87+ ),
88+ ),
89+ };
7490 }
7591
7692 public function parse ($ value , $ current ): CarbonInterval
0 commit comments