Created
July 14, 2016 13:20
-
-
Save sasezaki/78594016f3f2cbe0671e22fe84ef7424 to your computer and use it in GitHub Desktop.
AD to RegnalYear 西暦から元号に変換(元号新規追加されてもデータセットをコンテナ注入すればいい版)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* 西暦から元号に変換(元号新規追加されてもデータセットをコンテナ注入すればいい版) | |
* | |
* @see http://tohokuaiki.hateblo.jp/entry/20110314/1300090600 | |
* @see https://github.com/mattn/go-era_jp | |
*/ | |
declare(strict_types=1); | |
class YearValue | |
{ | |
private $gengo; | |
private $year; | |
private $toStringFormatter; | |
public function __construct(string $gengo, int $year, callable $toStringFormatter = null) | |
{ | |
$this->gengo = $gengo; | |
$this->year = $year; | |
$this->toStringFormatter = ($toStringFormatter) ? : function ($gengo, $year) { | |
return ($year === 1) ? "{$gengo}元年" : "{$gengo}{$year}年"; | |
}; | |
} | |
public function __toString() | |
{ | |
$formatter = $this->toStringFormatter; | |
return $formatter($this->gengo, $this->year); | |
} | |
} | |
class ADtoRegnalYear | |
{ | |
private $yearSet; | |
private $regnalYearFirst = 645; | |
private $formatter = null; | |
public function __construct(array $yearSet, $formatter = null) | |
{ | |
$this->yearSet = $yearSet; | |
$this->formatter = $formatter; | |
} | |
public function convert(int $year) : YearValue | |
{ | |
if ($year < $this->regnalYearFirst) return false; | |
foreach ($this->yearSet as $gengo => $years) { | |
if ($years['start'] <= $year && $year < $years['end']) { | |
return new YearValue($gengo, $year - $years['start'] + 1, $this->formatter); | |
} | |
} | |
} | |
} | |
// $container->setFactory(ADtoRegnalYear::class, function ($container) { | |
// return new ADtoRegnalYear(require_once $container->get('Config')['regnal_years']); | |
// }) | |
$regnalYearConverter = new ADtoRegnalYear([ | |
'昭和' => ['start' => 1926, 'end' => 1989], | |
'平成' => ['start' => 1989, 'end' => 9999] | |
]); | |
echo $regnalYearConverter->convert(1989); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment