<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\NotificationHandler;

use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberUtil;

class PhoneFormatter
{
    public function format(?string $phone, $stripPlus = true, string $defaultRegion = 'DE'): ?string
    {
        if (!$phone) {
            return null;
        }

        $phoneNumberUtil = PhoneNumberUtil::getInstance();

        try {
            $phoneNumberObject = $phoneNumberUtil->parse($phone, $defaultRegion);
        } catch (NumberParseException) {
            return null;
        }

        return substr($phoneNumberUtil->format($phoneNumberObject, PhoneNumberFormat::E164), (int) $stripPlus);
    }
}
