Skip to content

Commit 19cd028

Browse files
committed
Add customizable duration formatting with predefined constants
1 parent 8719bf3 commit 19cd028

1 file changed

Lines changed: 34 additions & 1 deletion

File tree

src/Model/Duration.php

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@
1515

1616
final class Duration implements \Stringable
1717
{
18+
public const string FORMAT_SHORT = 'hh:mm';
19+
public const string FORMAT_MEDIUM = 'hh:mm:ss';
20+
public const string FORMAT_LONG = 'DD.hh:mm:ss';
21+
public const string FORMAT_FULL = 'YY.MM.DD.hh:mm:ss';
22+
public static string $DEFAULT_FORMAT = self::FORMAT_MEDIUM;
23+
1824
/**
1925
* @var array{years: int, months: int, days: int, hours: int, minutes: int, seconds: int}|null
2026
*/
@@ -154,8 +160,35 @@ public function totalSeconds(): TimeUnitInterface
154160
return $this->value;
155161
}
156162

157-
public function format(string $format = 'D.mm:hh:ss'): string
163+
/**
164+
* Formats the duration according to the specified format string.
165+
*
166+
* Available format tokens:
167+
* - Y: Years (zero-padded)
168+
* - M: Months (zero-padded)
169+
* - D: Days (zero-padded)
170+
* - h: Hours (zero-padded)
171+
* - m: Minutes (zero-padded)
172+
* - s: Seconds (zero-padded)
173+
*
174+
* Predefined formats:
175+
* - FORMAT_SHORT: 'hh:mm'
176+
* - FORMAT_MEDIUM: 'hh:mm:ss'
177+
* - FORMAT_LONG: 'DD.hh:mm:ss'
178+
* - FORMAT_FULL: 'YY.MM.DD.hh:mm:ss'
179+
*
180+
* @param string|null $format The format string to use. If null, uses the default format (self::$DEFAULT_FORMAT)
181+
*
182+
* @return string The formatted duration string
183+
*
184+
* @throws \RuntimeException When formatting fails
185+
*/
186+
public function format(?string $format = null): string
158187
{
188+
if (null === $format) {
189+
$format = self::$DEFAULT_FORMAT;
190+
}
191+
159192
/**
160193
* @var array{years: int, months: int, days: int, hours: int, minutes: int, seconds: int} $decomposed
161194
*/

0 commit comments

Comments
 (0)