diff --git a/composer.json b/composer.json index 112e134..8429338 100644 --- a/composer.json +++ b/composer.json @@ -11,6 +11,7 @@ "license": "MIT", "require": { "php": "^7.1 || ^8.0", + "ext-json": "*", "giggsey/libphonenumber-for-php": "^7.0 || ^8.0" }, "require-dev": { diff --git a/src/PhoneNumber.php b/src/PhoneNumber.php index f1aaf8b..396bbac 100644 --- a/src/PhoneNumber.php +++ b/src/PhoneNumber.php @@ -4,13 +4,14 @@ namespace Brick\PhoneNumber; +use JsonSerializable; use libphonenumber\NumberParseException; use libphonenumber\PhoneNumberUtil; /** * A phone number. */ -class PhoneNumber +class PhoneNumber implements JsonSerializable { /** * The underlying PhoneNumber object from libphonenumber. @@ -203,6 +204,14 @@ public function isEqualTo(PhoneNumber $phoneNumber): bool return $this->phoneNumber->equals($phoneNumber->phoneNumber); } + /** + * Required by interface JsonSerializable. + */ + public function jsonSerialize(): string + { + return (string) $this; + } + /** * Returns a string representation of this phone number in international E164 format. * diff --git a/tests/PhoneNumberTest.php b/tests/PhoneNumberTest.php index 575ab6a..7029849 100644 --- a/tests/PhoneNumberTest.php +++ b/tests/PhoneNumberTest.php @@ -585,4 +585,13 @@ public function providerIsEqualTo(): array ['+442079460585', '+442079460586', false], ]; } + + public function testJsonSerializable(): void + { + $data = [ + 'phoneNumber' => PhoneNumber::parse('0123000000', 'FR') + ]; + + self::assertSame('{"phoneNumber":"+33123000000"}', json_encode($data)); + } }