odolbeau / phone-number-bundle

Integrates libphonenumber into your Symfony application
MIT License
217 stars 43 forks source link

Leading 0 in number form type with region code context #145

Open bk-tb opened 1 year ago

bk-tb commented 1 year ago

If the widget PhoneNumberType::WIDGET_COUNTRY_CHOICE is used, the number in the number form type contains leading zeros. In the context of the select form type of the region code this is unexpected: +49 02408 95660 instead of +49 2408 95660

Currently the PhoneNumberToArrayTransformer uses 'number' => $util->format($phoneNumber, PhoneNumberFormat::NATIONAL),

Perhaps the better way is to strip the leading zeros:

'number' => $this->getNationalNumberForRegionCodeContext($util->format($phoneNumber, PhoneNumberFormat::NATIONAL), $phoneNumber),

    private function getNationalNumberForRegionCodeContext(string $nationalNumber, PhoneNumber $phoneNumber): string
    {
        if (!$phoneNumber->hasItalianLeadingZero() && $phoneNumber->getNumberOfLeadingZeros() > 0 && str_starts_with($nationalNumber, str_repeat('0', $phoneNumber->getNumberOfLeadingZeros()))) {
            return substr($nationalNumber, $phoneNumber->getNumberOfLeadingZeros());
        }
        return $nationalNumber;
    }

Other numbers perhabs for unit tests: +43533765123 +41625571123 +390669812123 (hasItalianLeadingZero) +390863530123 +39393508123

ngrie commented 1 year ago

For reference, there already was an issue for this in the original repository: https://github.com/misd-service-development/phone-number-bundle/issues/174