From 95aa894d4b81c2dcef6294ee05c25297006826ee Mon Sep 17 00:00:00 2001 From: Frederik Bosch Date: Thu, 23 Nov 2017 12:33:11 +0100 Subject: [PATCH] add readable string method to address --- src/Address.php | 17 +++++++++++++++++ test/Unit/AddressTest.php | 16 ++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/Address.php b/src/Address.php index ac4a8cc6..b067e87b 100644 --- a/src/Address.php +++ b/src/Address.php @@ -99,6 +99,23 @@ public function __toString(): string return sprintf('%s <%s>', $encodedName, $this->address->getPunyCode()); } + /** + * @return string + */ + public function toReadableString(): string + { + if ($this->name === '') { + return (string)$this->address; + } + + $encodedName = $this->name; + if ($encodedName !== $this->name || preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $this->name) === 1) { + $encodedName = sprintf('"%s"', $encodedName); + } + + return sprintf('%s <%s>', $encodedName, $this->address->getAddress()); + } + /** * @param string $addressAsString * @return Address diff --git a/test/Unit/AddressTest.php b/test/Unit/AddressTest.php index 1ddfd1f7..02de09f7 100644 --- a/test/Unit/AddressTest.php +++ b/test/Unit/AddressTest.php @@ -103,6 +103,22 @@ public function it_parses_address_strings(string $addressString, bool $construct } } + /** + * @test + * @dataProvider provideAddressStrings + */ + public function it_can_be_converted_to_readable_string() + { + $address = new Address(new EmailAddress('local-part@münchen.com'), 'sprode, henriëtte'); + $this->assertEquals('"sprode, henriëtte" ', $address->toReadableString()); + + $address = new Address(new EmailAddress('local-part@münchen.com'), 'Frederik'); + $this->assertEquals('Frederik ', $address->toReadableString()); + + $address = new Address(new EmailAddress('local-part@münchen.com')); + $this->assertEquals('local-part@münchen.com', $address->toReadableString()); + } + /** * @return array */