Search code examples
symfonytwigcomparison

Integer comparison with Twig Symfony 4


I'm trying to do some comparisions using Twig on Symfony, in order to show a text with different style, but I'm getting a strange result. The value comes from my entity (Context) function :

    public function getDaysToExpire(): int
    {
        $creationDate = $this->created_at;
        $duration = $this->duration;
        $finalDate = $creationDate->modify('+' . $duration . ' days');
        $currentDate = new \DateTime();
        $difference = $currentDate->diff($finalDate);

        return $difference->days;
    }

It's working as expected and returning an integer as result.

On my Twig I have :

{% if context.getDaysToExpire > 5 %}
   <p class="context-days">Jours restants : {{ context.getDaysToExpire }}</p>
{% else %}
   <p class="context-days">Jours restants : <span class="bolder">{{ context.getDaysToExpire }}</span></p>
{% endif %}

If I don't use if clauses, I get the correct value from context.getDaysToExpire. However, with this code I get an strange result : + 30 for the first condition and + random values for the second one.

What I'm doing wrong ?


Solution

  • This should work

    public function getDaysToExpire(): int
    {
        $creationDate = clone $this->created_at; // prevent modification on $this->created_at
        $duration = $this->duration;
        $finalDate = $creationDate->modify('+' . $duration . ' days');
        $currentDate = new \DateTime();
        $difference = $currentDate->diff($finalDate);
    
        return $difference->days;
    }