Skip to content

Commit

Permalink
Implement JsonSerializable
Browse files Browse the repository at this point in the history
  • Loading branch information
BenMorel committed Aug 5, 2021
1 parent a4d57ff commit e74ed15
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"license": "MIT",
"require": {
"php": "^7.1 || ^8.0",
"ext-json": "*",
"giggsey/libphonenumber-for-php": "^7.0 || ^8.0"
},
"require-dev": {
Expand Down
11 changes: 10 additions & 1 deletion src/PhoneNumber.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
*
Expand Down
9 changes: 9 additions & 0 deletions tests/PhoneNumberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}

0 comments on commit e74ed15

Please sign in to comment.