diff --git a/README.md b/README.md index 250a1a7..2e7ede0 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ composer require michael-rubel/laravel-value-objects - [`ClassString`](https://github.com/michael-rubel/laravel-value-objects/blob/main/src/Collection/Complex/ClassString.php) - [`FullName`](https://github.com/michael-rubel/laravel-value-objects/blob/main/src/Collection/Complex/FullName.php) - [`Name`](https://github.com/michael-rubel/laravel-value-objects/blob/main/src/Collection/Complex/Name.php) +- [`Phone`](https://github.com/michael-rubel/laravel-value-objects/blob/main/src/Collection/Complex/Phone.php) - [`TaxNumber`](https://github.com/michael-rubel/laravel-value-objects/blob/main/src/Collection/Complex/TaxNumber.php) - [`Uuid`](https://github.com/michael-rubel/laravel-value-objects/blob/main/src/Collection/Complex/Uuid.php) @@ -140,6 +141,21 @@ $name->toArray(); // ['Company name!'] --- +### Phone +```php +$phone = new Phone(' +38 000 000 00 00 '); +$phone = Phone::make(' +38 000 000 00 00 '); +$phone = Phone::from(' +38 000 000 00 00 '); + +$phone->value(); // '+38 000 000 00 00' +(string) $phone; // '+38 000 000 00 00' +$phone->toArray(); // ['+38 000 000 00 00'] + +$phone->sanitized(); // '+380000000000' +``` + +--- + ### TaxNumber ```php $taxNumber = new TaxNumber('0123456789', 'PL'); diff --git a/src/Collection/Complex/Phone.php b/src/Collection/Complex/Phone.php index d17ea0f..4753cc4 100644 --- a/src/Collection/Complex/Phone.php +++ b/src/Collection/Complex/Phone.php @@ -40,6 +40,7 @@ public function __construct(protected string|Stringable $value) parent::__construct($this->value); $this->validate(); + $this->trim(); } /** @@ -50,8 +51,8 @@ public function __construct(protected string|Stringable $value) public function sanitized(): string { return str($this->value()) - ->replace(' ', '') ->replaceMatches('/\p{C}+/u', '') + ->replace(' ', '') ->value(); } @@ -66,4 +67,14 @@ protected function validate(): void throw ValidationException::withMessages([__('Your phone number is invalid.')]); } } + + /** + * Trim the value. + * + * @return void + */ + protected function trim(): void + { + $this->value = trim($this->value()); + } } diff --git a/tests/Unit/Complex/PhoneTest.php b/tests/Unit/Complex/PhoneTest.php index 520224f..d42b11f 100644 --- a/tests/Unit/Complex/PhoneTest.php +++ b/tests/Unit/Complex/PhoneTest.php @@ -16,6 +16,11 @@ $this->assertSame('+48000000000', $phone->value()); }); +test('phone is squished', function () { + $phone = new Phone(' +38 000 000 00 00 '); + $this->assertSame('+38 000 000 00 00', $phone->value()); +}); + test('phone allows short version', function () { $phone = new Phone('00000'); $this->assertSame('00000', $phone->value());