From 03172744a7d78655f9bf66bc16d39b337effb463 Mon Sep 17 00:00:00 2001 From: Kennedy Tedesco Date: Wed, 7 Aug 2019 15:30:56 -0300 Subject: [PATCH] Add email assertion (#113) --- README.md | 1 + src/Assert.php | 12 ++++++++++++ tests/AssertTest.php | 4 ++++ 3 files changed, 17 insertions(+) diff --git a/README.md b/README.md index 00bbb6e9..1b6299a4 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,7 @@ Method | Description `ip($value, $message = '')` | Check that a string is a valid IP (either IPv4 or IPv6) `ipv4($value, $message = '')` | Check that a string is a valid IPv4 `ipv6($value, $message = '')` | Check that a string is a valid IPv6 +`email($value, $message = '')` | Check that a string is a valid e-mail address `notWhitespaceOnly($value, $message = '')` | Check that a string contains at least one non-whitespace character ### File Assertions diff --git a/src/Assert.php b/src/Assert.php index f97d583e..bd463838 100644 --- a/src/Assert.php +++ b/src/Assert.php @@ -50,6 +50,7 @@ * @method static void nullOrIp($value, $message = '') * @method static void nullOrIpv4($value, $message = '') * @method static void nullOrIpv6($value, $message = '') + * @method static void nullOrEmail($value, $message = '') * @method static void nullOrUniqueValues($values, $message = '') * @method static void nullOrEq($value, $expect, $message = '') * @method static void nullOrNotEq($value, $expect, $message = '') @@ -131,6 +132,7 @@ * @method static void allIp($values, $message = '') * @method static void allIpv4($values, $message = '') * @method static void allIpv6($values, $message = '') + * @method static void allEmail($values, $message = '') * @method static void allUniqueValues($values, $message = '') * @method static void allEq($values, $expect, $message = '') * @method static void allNotEq($values, $expect, $message = '') @@ -501,6 +503,16 @@ public static function ipv6($value, $message = '') } } + public static function email($value, $message = '') + { + if (false === filter_var($value, FILTER_VALIDATE_EMAIL)) { + static::reportInvalidArgument(sprintf( + $message ?: 'Expected a value to be a valid e-mail address. Got %s', + static::valueToString($value) + )); + } + } + public static function uniqueValues(array $values, $message = '') { $allValues = count($values); diff --git a/tests/AssertTest.php b/tests/AssertTest.php index bd09ba4b..d5884feb 100644 --- a/tests/AssertTest.php +++ b/tests/AssertTest.php @@ -476,6 +476,10 @@ public function getTests() array('ipv6', array(array()), false), array('ipv6', array(null), false), array('ipv6', array(false), false), + array('email', array('foo'), false), + array('email', array(123), false), + array('email', array('foo.com'), false), + array('email', array('foo@bar.com'), true), array('uniqueValues', array(array('qwerty', 'qwerty')), false), array('uniqueValues', array(array('asdfg', 'qwerty')), true), array('uniqueValues', array(array(123, '123')), false),