Twig icon indicating copy to clipboard operation
Twig copied to clipboard

Make function existence deterministic in Twig `AppExtension`

Open ThomasLandauer opened this issue 4 years ago • 2 comments

'm just forwarding what @ondrejmirtes told me at https://github.com/phpstan/phpstan/issues/5640#issuecomment-921238545:

Calling twig_date_format_filter() in App\Twig\AppExtension sometimes leads to phpstan reporting

Function twig_date_format_filter not found

... and sometimes it doesn't ;-)

@ondrejmirtes at https://github.com/symfony/symfony/issues/43067#issuecomment-921596507:

This can usually be solved by separating functions into their own files and putting those files into Composer's autoload.files section.

ThomasLandauer avatar Sep 17 '21 11:09 ThomasLandauer

I don't think twig_date_format_filter is meant to be called directly in your own code.

In the past, functions implementing the built-in filters have been changed between Twig versions (for instance adding the environment as first argument and using needs_environment in their config). Twig provides BC for the signature of the Twig functions, but not for the signature of the PHP callable used to implement them.

@fabpot should we tag all those functions as @internal ?

stof avatar Dec 14 '21 17:12 stof

Well, I'm only using it to "fix" the date filter for null values:

public function dateFilter(Environment $environment, $date, string $format = 'F j, Y H:i:m'): string
{
    if (null === $date) {
        return '';
    }
    return twig_date_format_filter($environment, $date, $format);
}

Is there a better to do this (other than checking for is empty on every usage)?

ThomasLandauer avatar Dec 14 '21 22:12 ThomasLandauer

Fixed in Twig 4 where we don't have these functions anymore and their replacements are all internal methods.

fabpot avatar Dec 15 '23 06:12 fabpot