From f61eea9169e05c00dcf24aee7b96c8f4ff8f2972 Mon Sep 17 00:00:00 2001 From: Marcel Kapfer Date: Thu, 16 Sep 2021 22:45:25 +0200 Subject: [PATCH] PHPunit example --- src/Email.php | 33 +++++++++++++++++++++++++++++++++ tests/EmailTest.php | 27 +++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 src/Email.php create mode 100644 tests/EmailTest.php 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) + ); + } +}