YearList::useJpnGenGou()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
namespace Tuum\Form\Lists;
3
4
use Closure;
5
6
class YearList extends AbstractList
7
{
8
    /**
9
     * @param null|int $start
10
     * @param null|int $end
11
     * @param int      $step
12
     * @return YearList|static
13
     */
14
    public static function forge($start = null, $end = null, $step = 1)
15
    {
16
        return new self(
17
            $start ?: date('Y') - 1,
18
            $end ?: date('Y') + 1,
19
            $step,
20
            function ($year) {
21
                return sprintf('%04d', $year);
22
            });
23
    }
24
25
    /**
26
     * uses Japanese Gen-Gou style year, like '平成21年'.
27
     *
28
     * @return $this
29
     */
30
    public function useJpnGenGou()
31
    {
32
        return $this->setFormat(self::formatJpnGenGou());
33
    }
34
35
    /**
36
     * @return Closure
37
     */
38
    public static function formatJpnGenGou()
39
    {
40
        $genGou = [ // until => genGou name
41
            '1868' => false, // end of genGou, specified by false.
42
            '1911' => '明治',
43
            '1925' => '大正',
44
            '1988' => '昭和',
45
            '9999' => '平成', // so far...
46
        ];
47
        return function ($year) use ($genGou) {
48
            $year  = (int)$year;
49
            $start = 0;
50
            /** @var string|bool $gou */
51
            foreach ($genGou as $ends => $gou) {
52
                if ($year <= $ends) {
53
                    if ($gou === false) {
54
                        break;
55
                    }
56
                    $year = $year - $start;
57
                    if ($year == 1) {
58
                        $year = '元';
59
                    }
60
                    return $gou . $year . '年';
61
                }
62
                $start = $ends;
63
            }
64
            return '西暦' . $year . '年';
65
        };
66
    }
67
68
}