-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathPathAnalyzer.php
58 lines (44 loc) · 1.54 KB
/
PathAnalyzer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
declare(strict_types=1);
namespace Rector\Website\Blog\FileSystem;
use DateTimeInterface;
use Nette\Utils\DateTime;
use Nette\Utils\Strings;
use Rector\Website\Exception\ShouldNotHappenException;
use Symplify\SmartFileSystem\SmartFileInfo;
final class PathAnalyzer
{
/**
* @see https://regex101.com/r/UD1dMk/1
* @var string
*/
private const DATE_REGEX = '(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})';
/**
* @see https://regex101.com/r/2TMMR2/1
* @var string
*/
private const NAME_REGEX = '(?<name>[\w\d-]*)';
public function detectDate(SmartFileInfo $fileInfo): ?DateTimeInterface
{
$match = Strings::match($fileInfo->getFilename(), '#' . self::DATE_REGEX . '#');
if ($match === null) {
return null;
}
$date = sprintf('%d-%d-%d', $match['year'], $match['month'], $match['day']);
return DateTime::from($date);
}
public function getSlug(SmartFileInfo $fileInfo): string
{
$dateTime = $this->detectDate($fileInfo);
if (! $dateTime instanceof DateTimeInterface) {
throw new ShouldNotHappenException();
}
$dateAndNamePattern = sprintf('#%s-%s#', self::DATE_REGEX, self::NAME_REGEX);
$match = (array) Strings::match($fileInfo->getFilename(), $dateAndNamePattern);
$dateLessBreakDateTime = DateTime::from('2021-04-01');
if ($dateTime >= $dateLessBreakDateTime) {
return $match['name'];
}
return $dateTime->format('Y/m/d') . '/' . $match['name'];
}
}