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