|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Gnutix\StarWarsLibrary\Twig\Extension; |
|
6
|
|
|
|
|
7
|
|
|
use Twig\Extension\AbstractExtension; |
|
8
|
|
|
use Twig\TwigFilter; |
|
9
|
|
|
|
|
10
|
|
|
final class StarWarsExtension extends AbstractExtension |
|
11
|
|
|
{ |
|
12
|
|
|
public function getFilters(): array |
|
13
|
|
|
{ |
|
14
|
|
|
return [new TwigFilter('starWarsDate', [$this, 'transformToStarWarsDate'])]; |
|
15
|
|
|
} |
|
16
|
|
|
|
|
17
|
|
|
public function getName(): string |
|
18
|
|
|
{ |
|
19
|
|
|
return 'gnutix_star_wars_extension'; |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @param float|string|null $dateInput |
|
24
|
|
|
*/ |
|
25
|
|
|
public function transformToStarWarsDate($dateInput): string |
|
26
|
|
|
{ |
|
27
|
|
|
$date = trim((string) $dateInput); |
|
28
|
|
|
$suffixes = $this->getStarWarsDateSuffixes(); |
|
29
|
|
|
|
|
30
|
|
|
// Replace spaces between numbers by unbreakable spaces |
|
31
|
|
|
$date = (string) preg_replace('#([0-9.]+) ([0-9.]+)#', '$1 $2', $date); |
|
32
|
|
|
|
|
33
|
|
|
// For dates with a format "140" or "-3590" |
|
34
|
|
|
if (preg_match('#^-?(?:[0-9.]+)$#', $date)) { |
|
35
|
|
|
if (0 === strpos($date, '-')) { |
|
36
|
|
|
return substr($date, 1).$suffixes['BBY']; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
return $date.$suffixes['ABY']; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
// For dates already having BBY/ABY |
|
43
|
|
|
if (preg_match('# [AB]BY#', $date)) { |
|
44
|
|
|
// Replace any minus before a number |
|
45
|
|
|
$date = (string) preg_replace('#-([0-9.]+)#', '$1', $date); |
|
46
|
|
|
|
|
47
|
|
|
// Replace the suffixes |
|
48
|
|
|
return (string) preg_replace_callback( |
|
49
|
|
|
'# ([AB]BY)#', |
|
50
|
|
|
static function ($matches) use ($suffixes) { |
|
51
|
|
|
return $suffixes[$matches[1]]; |
|
52
|
|
|
}, |
|
53
|
|
|
$date |
|
54
|
|
|
); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
return $date; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
protected function getStarWarsDateSuffixes(): array |
|
61
|
|
|
{ |
|
62
|
|
|
return [ |
|
63
|
|
|
'BBY' => ' <abbr title="Before the Battle of Yavin IV">BBY</abbr>', |
|
64
|
|
|
'ABY' => ' <abbr title="After the Battle of Yavin IV">ABY</abbr>', |
|
65
|
|
|
]; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|