| Total Complexity | 5 |
| Total Lines | 32 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | <?php |
||
| 14 | class BlogPostDatePrefixHelper |
||
| 15 | { |
||
| 16 | /** |
||
| 17 | * We accept ISO 8601 dates in the format 'YYYY-MM-DD' and optionally a time in the format 'HH-MM', separated by a hyphen. |
||
| 18 | * |
||
| 19 | * @var string The regular expression pattern for matching a date prefix in a filename |
||
| 20 | */ |
||
| 21 | protected const DATE_PATTERN = '/^(\d{4}-\d{2}-\d{2})(?:-(\d{2}-\d{2}))?-/'; |
||
| 22 | |||
| 23 | public static function hasDatePrefix(string $filepath): bool |
||
| 24 | { |
||
| 25 | return preg_match(static::DATE_PATTERN, basename($filepath)) === 1; |
||
| 26 | } |
||
| 27 | |||
| 28 | public static function extractDate(string $filepath): DateTimeInterface |
||
| 29 | { |
||
| 30 | if (! preg_match(static::DATE_PATTERN, basename($filepath), $matches)) { |
||
| 31 | throw new InvalidArgumentException('The given filepath does not contain a valid ISO 8601 date prefix.'); |
||
| 32 | } |
||
| 33 | |||
| 34 | $dateString = $matches[1]; |
||
| 35 | |||
| 36 | if (isset($matches[2])) { |
||
| 37 | $dateString .= ' '.str_replace('-', ':', $matches[2]); |
||
| 38 | } |
||
| 39 | |||
| 40 | return new DateTime($dateString); |
||
| 41 | } |
||
| 42 | |||
| 43 | public static function stripDatePrefix(string $filepath): string |
||
| 46 | } |
||
| 47 | } |
||
| 48 |