Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
95.00% covered (success)
95.00%
19 / 20
75.00% covered (warning)
75.00%
3 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
InternationalPhoneNumber
95.00% covered (success)
95.00%
19 / 20
75.00% covered (warning)
75.00%
3 / 4
6
0.00% covered (danger)
0.00%
0 / 1
 validate
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 convert
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 toPhoneNumber
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 createRandom
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2namespace Apie\CountryAndPhoneNumber;
3
4use Apie\Core\Attributes\FakeMethod;
5use Apie\Core\ValueObjects\Exceptions\InvalidStringForValueObjectException;
6use Apie\Core\ValueObjects\Interfaces\StringValueObjectInterface;
7use Apie\Core\ValueObjects\IsStringValueObject;
8use Apie\CountryAndPhoneNumber\Factories\PhoneNumberFactory;
9use Faker\Generator;
10use libphonenumber\PhoneNumberFormat;
11use libphonenumber\PhoneNumberUtil;
12use PrinsFrank\Standards\Country\CountryAlpha2;
13use ReflectionClass;
14
15/**
16 * International phone number in E164 format.
17 */
18#[FakeMethod('createRandom')]
19final class InternationalPhoneNumber implements StringValueObjectInterface
20{
21    use IsStringValueObject;
22
23    public static function validate(string $input): void
24    {
25        $phoneUtil = PhoneNumberUtil::getInstance();
26        if (!$phoneUtil->isPossibleNumber($input)) {
27            throw new InvalidStringForValueObjectException($input, new ReflectionClass(__CLASS__));
28        }
29    }
30
31    protected function convert(string $input): string
32    {
33        $phoneUtil = PhoneNumberUtil::getInstance();
34        $phone = $phoneUtil->parse($input);
35        return $phoneUtil->format($phone, PhoneNumberFormat::E164);
36    }
37
38    public function toPhoneNumber(): PhoneNumber
39    {
40        $phoneUtil = PhoneNumberUtil::getInstance();
41        $phone = $phoneUtil->parse($this->internal);
42        return PhoneNumberFactory::createFrom(
43            $this->internal,
44            CountryAlpha2::from($phoneUtil->getRegionCodeForNumber($phone))
45        );
46    }
47
48    public static function createRandom(Generator $generator): self
49    {
50        $phoneNumber = '';
51        do {
52            $country = $generator->randomElement(CountryAlpha2::cases());
53            $phoneNumberUtil = PhoneNumberUtil::getInstance();
54            $phoneNumberObject = $phoneNumberUtil->getExampleNumber($country->value);
55            if ($phoneNumberObject) {
56                $phoneNumber = $phoneNumberUtil->format($phoneNumberObject, PhoneNumberFormat::E164);
57            }
58        } while ($phoneNumber === '');
59        return new InternationalPhoneNumber($phoneNumber);
60    }
61}