Passed
Push — master ( ad6b2a...b41ca0 )
by Caen
07:45 queued 14s
created

BlogPostDatePrefixHelper::hasDatePrefix()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Hyde\Framework\Features\Blogging;
6
7
use DateTime;
8
use DateTimeInterface;
9
use InvalidArgumentException;
10
11
/**
12
 * @internal Helper class for handling date prefixes in blog post filenames
13
 */
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
44
    {
45
        return preg_replace(static::DATE_PATTERN, '', basename($filepath));
46
    }
47
}
48