KnpLabs / KnpLabs/KnpTimeBundle
Allowing TimeHelper::diff to default to NULL (from datetime|ago twig filter) shows 'in -1 years' result
- Dominant language
- PHP
- Stars
- 625
- Forks
- 103
- PR merge metrics
- No merged PRs in 30d
Description
Issue #103 removed a test that would prove this (failing) test with an (almost) identical DateTime (compared to `time()`) for the `|ago` filter:
public function testFormatDiffDefaultToIsNull()
{
$from = new \DatetimeImmutable(date('Y-m-d H:i:s', time()));
$to = new \DateTime(null);
$this->assertEquals('diff.empty', $this->formatter->formatDiff($from, $to));
// actually returns 'diff.in.year' - or 'in -1 years' for English translation
}
In a live code scenario it would happen like this in a twig template (here, profile->updatedAt is a simple DateTime, with seconds resolution):
{# profile.updatedAt is a simple DateTime #}
Updated: {{ profile.updatedAt|ago() }}
But, the `ago()` uses the `profile.updatedAt` as the first parameter. and defaults to NULL as the second, from the twig filter TimeExtension::diff() (calling TimeHelper::diff()).
`TimeHelper::diff()`, via `getDatetimeObject()`, takes the null and makes it a DateTime(), defaulting to 'now' (with microseconds since PHP7.2):
return new DateTime(null);
Hence, the test above, which if you edit a profile and immediately show the `updatedAt|ago()` in a twig template can show 'in -1 Year' as the result.
If the default, in `getDatetimeObject()` was `return new DateTime(null ?? '@'.time());` solves the issue, but setting it to `DateTime('now')` would still fail because of the tiny difference in microseconds.
Contributor guide
No contributing guide indexed for this repository
Research direction
Start by locating TimeHelper::diff(), getDatetimeObject(), and the Twig TimeExtension::diff() path described in the issue. Reproduce the shown test with nearly identical DateTime values, then verify that a null default no longer produces a negative year result and that the diff.empty expectation passes.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- php
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100