polyfill icon indicating copy to clipboard operation
polyfill copied to clipboard

Intl Collator types are (slightly) incoherent

Open marien-probesys opened this issue 2 years ago • 2 comments

After installing the Form component which requires the symfony/polyfill-intl-icu package, I noticed that PHPStan started to complain about one of my method:

public function localeCompare(string $field1, string $field2): int
{
    $collator = new \Collator('fr_FR');
    $fieldsComparison = $collator->compare($field1, $field2);

    if ($fieldsComparison === false) {
        $fieldsComparison = strcmp($field1, $field2);
    }

    return $fieldsComparison;
}

The PHPStan output:

 ------ ----------------------------------------------------------------------- 
  Line   src/Service/Sorter/LocaleSorter.php                                    
 ------ ----------------------------------------------------------------------- 
  51     Method App\Service\Sorter\LocaleSorter::localeCompare() should return  
         int but returns int|true.                                              
 ------ -----------------------------------------------------------------------

It worked well before because \Collator::compare returns int|false.

However, the Collator class from this repo says that it returns int|bool.

I'm a bit surprised that Composer installed the symfony/polyfill-intl-icu package in first place. I have double-checked, and the PHP intl extension is correctly installed. But I don't know how Composer and polyfill work, so it may be normal :)

My workaround for now is to hardcode the type:

/** @var int|false */
$fieldsComparison = $collator->compare($field1, $field2);

I noticed more incoherent methods/functions: __construct, create, getAttribute, getErrorCode, getErrorMessage, getLocale, getSortKey and getStrength.

marien-probesys avatar Jan 10 '24 14:01 marien-probesys

This looks like a mistake in the phpdoc in this repo. Can you send a PR fixing it ?

stof avatar Jan 10 '24 15:01 stof

Yep, I can totally do that :+1:

marien-probesys avatar Jan 10 '24 16:01 marien-probesys