Skip to content

Allowing TimeHelper::diff to default to NULL (from datetime|ago twig filter) shows 'in -1 years' result #113

@alister

Description

@alister

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 #}
<p>Updated: {{ profile.updatedAt|ago() }}</p>

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions