diff --git a/src/Email.php b/src/Email.php new file mode 100644 index 0000000..ac3c74d --- /dev/null +++ b/src/Email.php @@ -0,0 +1,33 @@ +ensureIsValidEmail($email); + $this->email = $email; + } + + public static function fromString(string $email): self + { + return new self($email); + } + + public function __toString(): string + { + return $this->email; + } + + private function ensureIsValidEmail(string $email): void + { + if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { + throw new \InvalidArgumentException( + sprintf("%s is not a valid email address", $email) + ); + } + } +} diff --git a/tests/EmailTest.php b/tests/EmailTest.php new file mode 100644 index 0000000..696af28 --- /dev/null +++ b/tests/EmailTest.php @@ -0,0 +1,27 @@ +assertInstanceOf( + Email::class, + Email::fromString($this->email) + ); + } + + public function testCannotBeCreatedFromInvalidEmailAddress(): void { + $this->expectException(InvalidArgumentException::class); + Email::fromString('invalid'); + } + + public function testCanBeUsedAsString(): void { + $this->assertEquals( + $this->email, + Email::fromString($this->email) + ); + } +}