diff --git a/src/Year.php b/src/Year.php index ca6a29c..65948bc 100644 --- a/src/Year.php +++ b/src/Year.php @@ -10,6 +10,10 @@ use Brick\DateTime\Parser\IsoParsers; use JsonSerializable; +use function str_pad; + +use const STR_PAD_LEFT; + /** * Represents a year in the proleptic calendar. */ @@ -281,7 +285,14 @@ public function jsonSerialize(): string */ public function toISOString(): string { - return (string) $this->year; + // This code is optimized for high performance + return $this->year < 1000 && $this->year > -1000 + ? ( + $this->year < 0 + ? '-' . str_pad((string) -$this->year, 4, '0', STR_PAD_LEFT) + : str_pad((string) $this->year, 4, '0', STR_PAD_LEFT) + ) + : (string) $this->year; } /** diff --git a/tests/YearTest.php b/tests/YearTest.php index 59b8f0e..1ffdb18 100644 --- a/tests/YearTest.php +++ b/tests/YearTest.php @@ -516,7 +516,9 @@ public function testToString(int $year, string $expectedString): void public function providerToString(): array { return [ - [-100, '-100'], + [-100, '-0100'], + [100, '0100'], + [0, '0000'], [1987, '1987'], [105781, '105781'], ];