StarWarsExtension::getStarWarsDateSuffixes()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 5
rs 10
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&nbsp;$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' => '&nbsp;<abbr title="Before the Battle of Yavin IV">BBY</abbr>',
64
            'ABY' => '&nbsp;<abbr title="After the Battle of Yavin IV">ABY</abbr>',
65
        ];
66
    }
67
}
68