Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stringify years correctly according to ISO 8601 #90

Merged
merged 1 commit into from
Oct 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/Year.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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;
}

/**
Expand Down
4 changes: 3 additions & 1 deletion tests/YearTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
];
Expand Down