sonata-project / SonataIntlBundle

Symfony SonataIntlBundle
https://docs.sonata-project.org/projects/SonataIntlBundle
MIT License
213 stars 85 forks source link

Sonata\IntlBundle\Helper\BaseHelper::getLocale() problem #541

Closed temp closed 1 year ago

temp commented 2 years ago

Environment

Sonata packages

show

``` $ composer show --latest 'sonata-project/*' Info from https://repo.packagist.org: #StandWithUkraine Color legend: - patch or minor release available - update recommended - major release available - update possible - up to date version Direct dependencies: sonata-project/intl-bundle 2.13.0 2.13.0 Symfony SonataIntlBundle Transitive dependencies: Everything up to date ```

Symfony packages

show

``` $ composer show --latest 'symfony/*' Color legend: - patch or minor release available - update recommended - major release available - update possible - up to date version Direct dependencies: symfony/asset v5.4.7 v6.1.0 Manages URL generation and versioning of web assets such as CSS stylesheets, JavaScript files and image files symfony/browser-kit v5.4.11 v6.1.3 Simulates the behavior of a web browser, allowing you to make requests, click on links and submit forms programmatically symfony/console v5.4.11 v6.1.3 Eases the creation of beautiful and testable command line interfaces symfony/css-selector v5.4.11 v6.1.3 Converts CSS selectors to XPath expressions symfony/debug-bundle v5.4.11 v6.1.3 Provides a tight integration of the Symfony VarDumper component and the ServerLogCommand from MonologBridge into the Symfony full-stack framework symfony/doctrine-messenger v5.4.11 v6.1.3 Symfony Doctrine Messenger Bridge symfony/dotenv v5.4.5 v6.1.0 Registers environment variables from a .env file symfony/expression-language v5.4.11 v6.1.3 Provides an engine that can compile and evaluate expressions symfony/flex v2.2.3 v2.2.3 Composer plugin for Symfony symfony/form v5.4.11 v6.1.3 Allows to easily create, process and reuse HTML forms symfony/framework-bundle v5.4.11 v6.1.3 Provides a tight integration between Symfony components and the Symfony full-stack framework symfony/http-client v5.4.11 v6.1.3 Provides powerful methods to fetch HTTP resources synchronously or asynchronously symfony/intl v5.4.11 v6.1.0 Provides a PHP replacement layer for the C intl extension that includes additional data from the ICU library symfony/mailer v5.4.11 v6.1.3 Helps sending emails symfony/maker-bundle v1.45.0 v1.45.0 Symfony Maker helps you create empty commands, controllers, form classes, tests and more so you can forget about writing boilerplate code. symfony/mime v5.4.11 v6.1.3 Allows manipulating MIME messages symfony/monolog-bundle v3.8.0 v3.8.0 Symfony MonologBundle symfony/notifier v5.4.8 v6.1.0 Sends notifications via one or more channels (email, SMS, ...) symfony/phpunit-bridge v6.1.3 v6.1.3 Provides utilities for PHPUnit, especially user deprecation notices management symfony/process v5.4.11 v6.1.3 Executes commands in sub-processes symfony/property-access v5.4.11 v6.1.3 Provides functions to read and write from/to an object or array using a simple string notation symfony/property-info v5.4.11 v6.1.3 Extracts information about PHP class' properties using metadata of popular sources symfony/proxy-manager-bridge v5.4.6 v6.1.0 Provides integration for ProxyManager with various Symfony components symfony/runtime v5.4.11 v6.1.3 Enables decoupling PHP applications from global state symfony/security-bundle v5.4.11 v6.1.3 Provides a tight integration of the Security component into the Symfony full-stack framework symfony/serializer v5.4.11 v6.1.3 Handles serializing and deserializing data structures, including object graphs, into array structures or other formats like XML and JSON. symfony/stopwatch v5.4.5 v6.1.0 Provides a way to profile code symfony/string v5.4.11 v6.1.3 Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way symfony/translation v5.4.11 v6.1.3 Provides tools to internationalize your application symfony/twig-bundle v5.4.8 v6.1.1 Provides a tight integration of Twig into the Symfony full-stack framework symfony/validator v5.4.11 v6.1.3 Provides tools to validate values symfony/web-link v5.4.3 v6.1.0 Manages links between resources symfony/web-profiler-bundle v5.4.10 v6.1.2 Provides a development tool that gives detailed information about the execution of any request symfony/yaml v5.4.11 v6.1.3 Loads and dumps YAML files Transitive dependencies: symfony/amqp-messenger v5.4.11 v5.4.11 Symfony AMQP extension Messenger Bridge symfony/cache v5.4.11 v6.1.3 Provides an extended PSR-6, PSR-16 (and tags) implementation symfony/cache-contracts v2.5.2 v3.1.1 Generic abstractions related to caching symfony/config v5.4.11 v6.1.3 Helps you find, load, combine, autofill and validate configuration values of any kind symfony/dependency-injection v5.4.11 v6.1.3 Allows you to standardize and centralize the way objects are constructed in your application symfony/deprecation-contracts v3.1.1 v3.1.1 A generic function and convention to trigger deprecation notices symfony/doctrine-bridge v5.4.11 v6.1.3 Provides integration for Doctrine with various Symfony components symfony/dom-crawler v5.4.11 v6.1.3 Eases DOM navigation for HTML and XML documents symfony/error-handler v5.4.11 v6.1.3 Provides tools to manage errors and ease debugging PHP code symfony/event-dispatcher v5.4.9 v6.1.0 Provides tools that allow your application components to communicate with each other by dispatching events and listening to them symfony/event-dispatcher-contracts v3.1.1 v3.1.1 Generic abstractions related to dispatching event symfony/filesystem v5.4.11 v6.1.3 Provides basic utilities for the filesystem symfony/finder v5.4.11 v6.1.3 Finds files and directories via an intuitive fluent interface symfony/http-client-contracts v2.5.2 v3.1.1 Generic abstractions related to HTTP clients symfony/http-foundation v5.4.11 v6.1.3 Defines an object-oriented layer for the HTTP specification symfony/http-kernel v5.4.11 v6.1.3 Provides a structured process for converting a Request into a Response symfony/messenger v5.4.11 v6.1.3 Helps applications send and receive messages to/from other applications or via message queues symfony/monolog-bridge v5.4.10 v6.1.2 Provides integration for Monolog with various Symfony components symfony/options-resolver v5.4.11 v6.1.0 Provides an improved replacement for the array_replace PHP function symfony/password-hasher v5.4.11 v6.1.3 Provides password hashing utilities symfony/polyfill-intl-grapheme v1.26.0 v1.26.0 Symfony polyfill for intl's grapheme_* functions symfony/polyfill-intl-icu v1.26.0 v1.26.0 Symfony polyfill for intl's ICU-related data and classes symfony/polyfill-intl-idn v1.26.0 v1.26.0 Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions symfony/polyfill-intl-normalizer v1.26.0 v1.26.0 Symfony polyfill for intl's Normalizer class and related functions symfony/polyfill-mbstring v1.26.0 v1.26.0 Symfony polyfill for the Mbstring extension symfony/polyfill-php73 v1.26.0 v1.26.0 Symfony polyfill backporting some PHP 7.3+ features to lower PHP versions symfony/polyfill-php80 v1.26.0 v1.26.0 Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions symfony/polyfill-php81 v1.26.0 v1.26.0 Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions symfony/redis-messenger v5.4.6 v5.4.6 Symfony Redis extension Messenger Bridge symfony/routing v5.4.11 v6.1.3 Maps an HTTP request to a set of configuration variables symfony/security-core v5.4.11 v6.1.3 Symfony Security Component - Core Library symfony/security-csrf v5.4.11 v6.1.0 Symfony Security Component - CSRF Library symfony/security-guard v5.4.9 v5.4.9 Symfony Security Component - Guard symfony/security-http v5.4.11 v6.1.3 Symfony Security Component - HTTP Integration symfony/service-contracts v2.5.2 v3.1.1 Generic abstractions related to writing services symfony/translation-contracts v2.5.2 v3.1.1 Generic abstractions related to translation symfony/twig-bridge v5.4.11 v6.1.3 Provides integration for Twig with various Symfony components symfony/var-dumper v5.4.11 v6.1.3 Provides mechanisms for walking through any arbitrary PHP variable symfony/var-exporter v5.4.10 v6.1.3 Allows exporting any serializable PHP data structure to plain PHP code ```

PHP version

$ php -v
PHP 8.1.9 (cli) (built: Aug  7 2022 23:18:24) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.9, Copyright (c) Zend Technologies

Subject

We upgraded from 2.12.x to 2.13, migrated from Templating\Helper to the new Helper classes and are experiencing problems with getLocale().

We have a class injects Sonata\IntlBundle\Helper\NumberFormatterInterface and calls formatDecimal(123), which results in this error:

Sonata\IntlBundle\Helper\BaseHelper::getLocale(): Return value must be of type string, null returned

We digged into the problem and it seems like BaseHelper::setLocale() is never called, which should be done by \Symfony\Component\HttpKernel\EventListener\LocaleAwareListener, which receives the locale aware listeners from \Symfony\Component\HttpKernel\DependencyInjection\RegisterLocaleAwareServicesPass via the kernel.locale_aware tag.

Seems like the Helpers are missing this tag. When we add it manually to config/intl.php, or add a ->autoconfigure() it works as expected.

Steps to reproduce

We installed a symfony 5.4 website skeleton, installed sonata-project/intl-bundle, and simply added this controller:

<?php

namespace App\Controller;

use Sonata\IntlBundle\Helper\NumberFormatterInterface;
use Symfony\Component\Routing\Annotation\Route;

class DefaultController
{
    private NumberFormatterInterface $formatter;

    public function __construct(
        NumberFormatterInterface $formatter,
    ) {
        $this->formatter = $formatter;
    }

    #[Route('/foo')]
    public function __invoke()
    {
        echo $this->formatter->formatDecimal(123);

        die;
    }
}

Which will yield the above error.

VincentLanglet commented 2 years ago

Can you do a PR @temp ?

cc @Hanmac which introduce the changes

temp commented 2 years ago

Yes, but I don't know which solution you would prefer. Manual tag, or autoconfigure?

Hanmac commented 2 years ago

I thought the interface would have been enough

Imo we could do auto configuration, but manual would be fine too

temp commented 2 years ago

Interface + autoconfigure adds the tag. I'll add the manual tag, since this is also done with twig.extension

AntoineRoue commented 1 year ago

I would like to reopen this issue, because the same problem with the same code occurs when getLocale is called from a command. I'm using Symfony 4.4, not sure if it changes something.

Code :

<?php

namespace App\Command;

use Sonata\IntlBundle\Helper\NumberFormatterInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class IntlCommand extends Command
{
    private NumberFormatterInterface $formatter;

    public function __construct(NumberFormatterInterface $formatter)
    {
        parent::__construct();
        $this->formatter = $formatter;
    }

    public function configure()
    {
        $this->setName('intl');
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        echo $this->formatter->formatDecimal(123);
        die;
    }
}

Result when calling this command : Return value of Sonata\IntlBundle\Helper\BaseHelper::getLocale() must be of the type string, null returned

VincentLanglet commented 1 year ago

There is no local set in a command, so the error is not surprising. With which local do you expect to format the decimal ?

Code can be changed to

    public function getLocale(): string
    {
        return $this->locale ?? '';
    }

but I'm not sure how will work the NumberFormatter without locale https://www.php.net/manual/en/class.numberformatter.php

AntoineRoue commented 1 year ago

It could use sonata_intl.locale or framework.default_locale. I expected a config in sonata_intl to solve this problem.

VincentLanglet commented 1 year ago

If you use an older version (the 2.12 maybe) and try to dump the locale, what is the result ?

Edit: I found, this was used https://github.com/sonata-project/SonataIntlBundle/blob/2.12.0/src/DependencyInjection/SonataIntlExtension.php#L90-L91

This is a regression.

VincentLanglet commented 1 year ago

I've tried to fix it in https://github.com/sonata-project/SonataIntlBundle/pull/565 if you can try the branch.

AntoineRoue commented 1 year ago

It works !

VincentLanglet commented 1 year ago

Will be released as 2.14.1 and I'll merge the fix in 3.x branch after.