Refactor rules related to age

The "Age" rule was removed because it had too many responsibilities.
Instead "MaximumAge" was created (since there is already "MinimumAge").

This commit also introduces "AbstractAge" rule that is been used in both
mentioned rules.
This commit is contained in:
Henrique Moody 2018-01-29 14:23:30 +01:00
parent 51ce465b8c
commit 8d44bc3407
No known key found for this signature in database
GPG key ID: 221E9281655813A6
26 changed files with 468 additions and 588 deletions

View file

@ -1,52 +0,0 @@
# Age
- `Age(int $minAge)`
- `Age(int $minAge, int $maxAge)`
- `Age(null, int $maxAge)`
Validates ranges of years.
The validated values can be any date value; internally they will be transformed
into [DateTime](http://php.net/manual/en/class.datetime.php) objects according
to the defined locale settings.
The examples below validate if the given dates are lower or equal to 18 years ago:
```php
v::age(18)->validate('17 years ago'); // false
v::age(18)->validate('18 years ago'); // true
v::age(18)->validate('19 years ago'); // true
v::age(18)->validate('1970-01-01'); // true
v::age(18)->validate('today'); // false
```
The examples below validate if the given dates are between 10 and 50 years ago:
```php
v::age(10, 50)->validate('9 years ago'); // false
v::age(10, 50)->validate('10 years ago'); // true
v::age(10, 50)->validate('30 years ago'); // true
v::age(10, 50)->validate('50 years ago'); // true
v::age(10, 50)->validate('51 years ago'); // false
```
The examples below validate if the given dates are greater than or equal to 70 years ago:
```php
v::age(null, 70)->validate('today'); // true
v::age(null, 70)->validate('70 years ago'); // true
v::age(null, 70)->validate('71 years ago'); // false
```
Message template for this validator includes `{{minAge}}` and `{{maxAge}}`.
## Changelog
Version | Description
--------|-------------
0.9.0 | Created based on deprecated `MinimumAge` rule
***
See also:
- [Between](Between.md)
- [DateTime](DateTime.md)
- [Max](Max.md)
- [Min](Min.md)

38
docs/MaximumAge.md Normal file
View file

@ -0,0 +1,38 @@
# MaximumAge
- `MaximumAge(int $age)`
- `MaximumAge(int $age, string $format)`
Validates a maximum age for a given date. The `$format` argument should be in
accordance to PHP's [date()][] function. When `$format` is not given this rule
accepts [Supported Date and Time Formats][] by PHP (see [strtotime()][]).
```php
v::maximumAge(12)->validate('12 years ago'); // true
v::maximumAge(12, 'Y-m-d')->validate('2013-07-31'); // true
v::maximumAge(12)->validate('13 years ago'); // false
v::maximumAge(18, 'Y-m-d')->validate('1988-09-09'); // false
```
Using [Date](Date.md) before is a best-practice.
This rule does not accepts instances of [DateTimeInterface][].
## Changelog
Version | Description
--------|-------------
2.0.0 | Created based on removed `Age` rule
***
See also:
- [Date](Date.md)
- [Max](Max.md)
- [Min](Min.md)
- [MinimumAge](MinimumAge.md)
[date()]: http://php.net/date
[DateTimeInterface]: http://php.net/DateTimeInterface
[strtotime()]: http://php.net/strtotime
[Supported Date and Time Formats]: http://php.net/datetime.formats

View file

@ -1,20 +1,22 @@
# MinimumAge
This is going to be deprecated, please use [Age](Age.md) instead.
- `MinimumAge(int $age)`
- `MinimumAge(int $age, string $format)`
Validates a minimum age for a given date.
Validates a minimum age for a given date. The `$format` argument should be in
accordance to PHP's [date()][] function. When `$format` is not given this rule
accepts [Supported Date and Time Formats][] by PHP (see [strtotime()][]).
```php
v::minimumAge(18)->validate('1987-01-01'); // true
v::minimumAge(18, 'd/m/Y')->validate('01/01/1987'); // true
v::minimumAge(18)->validate('18 years ago'); // true
v::minimumAge(18, 'Y-m-d')->validate('1987-01-01'); // true
v::minimumAge(18)->validate('17 years ago'); // false
v::minimumAge(18, 'Y-m-d')->validate('2010-09-07'); // false
```
Using [DateTime](DateTime.md) before is a best-practice.
Message template for this validator includes `{{age}}`.
Using [Date](Date.md) before is a best-practice.
This rule does not accepts instances of [DateTimeInterface][].
## Changelog
@ -25,5 +27,12 @@ Version | Description
***
See also:
- [Age](Age.md)
- [DateTime](DateTime.md)
- [Date](Date.md)
- [Max](Max.md)
- [MaximumAge](MaximumAge.md)
- [Min](Min.md)
[date()]: http://php.net/date
[DateTimeInterface]: http://php.net/DateTimeInterface
[strtotime()]: http://php.net/strtotime
[Supported Date and Time Formats]: http://php.net/datetime.formats

View file

@ -1,47 +0,0 @@
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Respect\Validation\Exceptions;
class AgeException extends NestedValidationException
{
const BOTH = 0;
const LOWER = 1;
const GREATER = 2;
public static $defaultTemplates = [
self::MODE_DEFAULT => [
self::BOTH => '{{name}} must be between {{minAge}} and {{maxAge}} years ago',
self::LOWER => '{{name}} must be lower than {{minAge}} years ago',
self::GREATER => '{{name}} must be greater than {{maxAge}} years ago',
],
self::MODE_NEGATIVE => [
self::BOTH => '{{name}} must not be between {{minAge}} and {{maxAge}} years ago',
self::LOWER => '{{name}} must not be lower than {{minAge}} years ago',
self::GREATER => '{{name}} must not be greater than {{maxAge}} years ago',
],
];
public function chooseTemplate()
{
if (!$this->getParam('minAge')) {
return static::GREATER;
}
if (!$this->getParam('maxAge')) {
return static::LOWER;
}
return static::BOTH;
}
}

View file

@ -0,0 +1,32 @@
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Respect\Validation\Exceptions;
/**
* @author Henrique Moody <henriquemoody@gmail.com>
*/
final class MaximumAgeException extends ValidationException
{
/**
* {@inheritdoc}
*/
public static $defaultTemplates = [
self::MODE_DEFAULT => [
self::STANDARD => '{{name}} must be {{age}} years or less',
],
self::MODE_NEGATIVE => [
self::STANDARD => '{{name}} must not be {{age}} years or less',
],
];
}

View file

@ -13,14 +13,21 @@ declare(strict_types=1);
namespace Respect\Validation\Exceptions;
class MinimumAgeException extends ValidationException
/**
* @author Henrique Moody <henriquemoody@gmail.com>
* @author Jean Pimentel <jeanfap@gmail.com>
*/
final class MinimumAgeException extends ValidationException
{
/**
* {@inheritdoc}
*/
public static $defaultTemplates = [
self::MODE_DEFAULT => [
self::STANDARD => 'The age must be {{age}} years or more.',
self::STANDARD => '{{input}} must be {{age}} years or more',
],
self::MODE_NEGATIVE => [
self::STANDARD => 'The age must not be {{age}} years or more.',
self::STANDARD => '{{input}} must not be {{age}} years or more',
],
];
}

View file

@ -0,0 +1,109 @@
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use Respect\Validation\Helpers\DateTimeHelper;
use function date;
use function date_parse_from_format;
use function is_scalar;
use function strtotime;
use function vsprintf;
/**
* Abstract class to validate ages.
*
* @author Henrique Moody <henriquemoody@gmail.com>
*/
abstract class AbstractAge extends AbstractRule
{
use DateTimeHelper;
/**
* @var int
*/
private $age;
/**
* @var string|null
*/
private $format;
/**
* @var int
*/
private $baseDate;
/**
* Initializes the rule.
*
* @param int $age
* @param string|null $format
*/
public function __construct(int $age, string $format = null)
{
$this->age = $age;
$this->format = $format;
$this->baseDate = date('Ymd') - $this->age * 10000;
}
/**
* Should compare the current base date with the given one.
*
* The dates are represented as integers in the format "Ymd".
*
* @param int $baseDate
* @param int $givenDate
*
* @return bool
*/
abstract protected function compare(int $baseDate, int $givenDate): bool;
/**
* {@inheritdoc}
*/
public function validate($input): bool
{
if (!is_scalar($input)) {
return false;
}
if (null === $this->format) {
return $this->isValidWithoutFormat((string) $input);
}
return $this->isValidWithFormat($this->format, (string) $input);
}
private function isValidWithoutFormat(string $dateTime): bool
{
$timestamp = strtotime($dateTime);
if (false === $timestamp) {
return false;
}
return $this->compare($this->baseDate, (int) date('Ymd', $timestamp));
}
private function isValidWithFormat(string $format, string $dateTime): bool
{
if (!$this->isDateTime($format, $dateTime)) {
return false;
}
return $this->compare(
$this->baseDate,
(int) vsprintf('%d%02d%02d', date_parse_from_format($format, $dateTime))
);
}
}

View file

@ -1,79 +0,0 @@
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use DateTime as DateTimeMutable;
use Respect\Validation\Exceptions\ComponentException;
/**
* @todo Do not extend AllOf
*/
class Age extends AllOf
{
public $minAge;
public $maxAge;
public function __construct($minAge = null, $maxAge = null)
{
if (null === $minAge && null === $maxAge) {
throw new ComponentException('An age interval must be provided');
}
if (null !== $minAge && null !== $maxAge && $maxAge <= $minAge) {
throw new ComponentException(sprintf('%d cannot be greater than or equals to %d', $minAge, $maxAge));
}
$this->setMinAge($minAge);
$this->setMaxAge($maxAge);
}
private function createDateTimeFromAge($age)
{
$interval = sprintf('-%d years', $age);
return new DateTimeMutable($interval);
}
private function setMaxAge($maxAge): void
{
$this->maxAge = $maxAge;
if (null === $maxAge) {
return;
}
$minDate = $this->createDateTimeFromAge($maxAge);
$minDate->setTime(0, 0, 0);
$minRule = new Min($minDate, true);
$this->addRule($minRule);
}
private function setMinAge($minAge): void
{
$this->minAge = $minAge;
if (null === $minAge) {
return;
}
$maxDate = $this->createDateTimeFromAge($minAge);
$maxDate->setTime(23, 59, 59);
$maxRule = new Max($maxDate, true);
$this->addRule($maxRule);
}
}

View file

@ -0,0 +1,30 @@
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
/**
* Validates a maximum age for a given date.
*
* @author Henrique Moody <henriquemoody@gmail.com>
*/
final class MaximumAge extends AbstractAge
{
/**
* {@inheritdoc}
*/
protected function compare(int $baseDate, int $givenDate): bool
{
return $baseDate <= $givenDate;
}
}

View file

@ -13,39 +13,20 @@ declare(strict_types=1);
namespace Respect\Validation\Rules;
use DateTimeImmutable;
use DateTimeInterface;
use Respect\Validation\Exceptions\ComponentException;
class MinimumAge extends AbstractRule
/**
* Validates a minimum age for a given date.
*
* @author Henrique Moody <henriquemoody@gmail.com>
* @author Jean Pimentel <jeanfap@gmail.com>
* @author Kennedy Tedesco <kennedyt.tw@gmail.com>
*/
final class MinimumAge extends AbstractAge
{
public $age = null;
public $format = null;
public function __construct($age, $format = null)
/**
* {@inheritdoc}
*/
protected function compare(int $baseDate, int $givenDate): bool
{
if (!filter_var($age, FILTER_VALIDATE_INT)) {
throw new ComponentException('The age must be a integer value.');
}
$this->age = $age;
$this->format = $format;
}
public function validate($input): bool
{
if ($input instanceof DateTimeInterface) {
$birthday = new DateTimeImmutable('now - '.$this->age.' year');
return $birthday > $input;
}
if (!is_string($input) || (is_null($this->format) && false === strtotime($input))) {
return false;
}
$age = ((date('Ymd') - date('Ymd', (int) strtotime($input))) / 10000);
return $age >= $this->age;
return $baseDate >= $givenDate;
}
}

View file

@ -21,7 +21,6 @@ use Respect\Validation\Rules\AllOf;
use Respect\Validation\Rules\Key;
/**
* @method static Validator age(int $minAge = null, int $maxAge = null)
* @method static Validator allOf(Validatable ...$rule)
* @method static Validator alnum(string $additionalChars = null)
* @method static Validator alpha(string $additionalChars = null)
@ -97,6 +96,7 @@ use Respect\Validation\Rules\Key;
* @method static Validator luhn()
* @method static Validator macAddress()
* @method static Validator max(mixed $maxValue, bool $inclusive = true)
* @method static Validator maximumAge(int $age, string $format = null)
* @method static Validator mimetype(string $mimetype)
* @method static Validator min(mixed $minValue, bool $inclusive = true)
* @method static Validator minimumAge(int $age, bool $format = null)

View file

@ -12,7 +12,7 @@ $user->name = 'Alexandre';
$user->birthdate = '1987-07-01';
$userValidator = v::attribute('name', v::stringType()->length(1, 32))
->attribute('birthdate', v::dateTime()->age(18));
->attribute('birthdate', v::dateTime()->minimumAge(18));
$userValidator->assert($user);
?>

View file

@ -1,11 +0,0 @@
--FILE--
<?php
require 'vendor/autoload.php';
use Respect\Validation\Validator as v;
v::age(18)->assert('18 years ago');
v::age(18)->check('18 years ago');
?>
--EXPECTF--

View file

@ -1,17 +0,0 @@
--FILE--
<?php
require 'vendor/autoload.php';
use Respect\Validation\Exceptions\MaxException;
use Respect\Validation\Validator as v;
try {
v::age(18)->check('17 years ago');
} catch (MaxException $e) {
echo $e->getMainMessage();
}
?>
--EXPECTF--
"17 years ago" must be less than or equal to `[date-time] (DateTime: "%s")`

View file

@ -1,17 +0,0 @@
--FILE--
<?php
require 'vendor/autoload.php';
use Respect\Validation\Exceptions\AllOfException;
use Respect\Validation\Validator as v;
try {
v::age(18)->assert('17 years ago');
} catch (AllOfException $e) {
echo $e->getFullMessage();
}
?>
--EXPECTF--
- "17 years ago" must be less than or equal to `[date-time] (DateTime: "%s")`

View file

@ -1,17 +0,0 @@
--FILE--
<?php
require 'vendor/autoload.php';
use Respect\Validation\Exceptions\AllOfException;
use Respect\Validation\Validator as v;
try {
v::age(10, 50)->assert('9 years ago');
} catch (AllOfException $e) {
echo $e->getFullMessage();
}
?>
--EXPECTF--
- "9 years ago" must be less than or equal to `[date-time] (DateTime: "%s")`

View file

@ -0,0 +1,37 @@
--FILE--
<?php
require 'vendor/autoload.php';
use Respect\Validation\Exceptions\MaximumAgeException;
use Respect\Validation\Exceptions\NestedValidationException;
use Respect\Validation\Validator as v;
try {
v::maximumAge(12)->check('50 years ago');
} catch (MaximumAgeException $exception) {
echo $exception->getMessage().PHP_EOL;
}
try {
v::not(v::maximumAge(12))->check('11 years ago');
} catch (MaximumAgeException $exception) {
echo $exception->getMessage().PHP_EOL;
}
try {
v::maximumAge(12, 'Y-m-d')->assert('1988-09-09');
} catch (NestedValidationException $exception) {
echo $exception->getFullMessage().PHP_EOL;
}
try {
v::not(v::maximumAge(12, 'Y-m-d'))->assert('2018-01-01');
} catch (NestedValidationException $exception) {
echo $exception->getFullMessage().PHP_EOL;
}
?>
--EXPECTF--
"50 years ago" must be 12 years or less
"11 years ago" must not be 12 years or less
- "1988-09-09" must be 12 years or less
- "2018-01-01" must not be 12 years or less

View file

@ -0,0 +1,39 @@
--FILE--
<?php
require 'vendor/autoload.php';
date_default_timezone_set('UTC');
use Respect\Validation\Exceptions\MinimumAgeException;
use Respect\Validation\Exceptions\NestedValidationException;
use Respect\Validation\Validator as v;
try {
v::minimumAge(18)->check('17 years ago');
} catch (MinimumAgeException $exception) {
echo $exception->getMessage().PHP_EOL;
}
try {
v::not(v::minimumAge(18))->check('-30 years');
} catch (MinimumAgeException $exception) {
echo $exception->getMessage().PHP_EOL;
}
try {
v::minimumAge(18)->assert('yesterday');
} catch (NestedValidationException $exception) {
echo $exception->getFullMessage().PHP_EOL;
}
try {
v::minimumAge(18, 'd/m/Y')->assert('12/10/2010');
} catch (NestedValidationException $exception) {
echo $exception->getFullMessage().PHP_EOL;
}
?>
--EXPECTF--
"17 years ago" must be 18 years or more
"-30 years" must not be 18 years or more
- "yesterday" must be 18 years or more
- "12/10/2010" must be 18 years or more

View file

@ -1,13 +0,0 @@
--FILE--
<?php
require 'vendor/autoload.php';
date_default_timezone_set('UTC');
use Respect\Validation\Validator as v;
v::MinimumAge(12)->assert(new DateTime('1999-10-12'));
v::MinimumAge(12)->check(new DateTime('1999-10-12'));
?>
--EXPECTF--

View file

@ -1,18 +0,0 @@
--FILE--
<?php
require 'vendor/autoload.php';
date_default_timezone_set('UTC');
use Respect\Validation\Exceptions\MinimumAgeException;
use Respect\Validation\Validator as v;
try {
v::MinimumAge(12)->check(new DateTime('2010-10-12'));
} catch (MinimumAgeException $exception) {
echo $exception->getMainMessage();
}
?>
--EXPECTF--
The age must be 12 years or more.

View file

@ -1,12 +0,0 @@
--FILE--
<?php
require 'vendor/autoload.php';
date_default_timezone_set('UTC');
use Respect\Validation\Validator as v;
v::MinimumAge(12, 'd/m/Y')->check('12/10/1999');
?>
--EXPECTF--

View file

@ -1,18 +0,0 @@
--FILE--
<?php
require 'vendor/autoload.php';
date_default_timezone_set('UTC');
use Respect\Validation\Exceptions\AllOfException;
use Respect\Validation\Validator as v;
try {
v::MinimumAge(12, 'd/m/Y')->assert('12/10/2010');
} catch (AllOfException $exception) {
echo $exception->getFullMessage();
}
?>
--EXPECTF--
- The age must be 12 years or more.

View file

@ -0,0 +1,69 @@
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Respect\Validation\Test\Rules;
use DateTime;
use DateTimeImmutable;
use Respect\Validation\Rules\MaximumAge;
use Respect\Validation\Test\RuleTestCase;
use stdClass;
use function date;
use function strtotime;
/**
* @group rule
*
* @covers \Respect\Validation\Rules\MaximumAge
* @covers \Respect\Validation\Rules\AbstractAge
*
* @author Henrique Moody <henriquemoody@gmail.com>
*/
final class MaximumAgeTest extends RuleTestCase
{
/**
* {@inheritdoc}
*/
public function providerForValidInput(): array
{
return [
[new MaximumAge(30, 'Y-m-d'), date('Y-m-d', strtotime('30 years ago'))],
[new MaximumAge(30, 'Y-m-d'), date('Y-m-d', strtotime('29 years ago'))],
[new MaximumAge(30), '30 years ago'],
[new MaximumAge(30), '29 years ago'],
];
}
/**
* {@inheritdoc}
*/
public function providerForInvalidInput(): array
{
return [
[new MaximumAge(30), new DateTime('30 years ago')],
[new MaximumAge(30), new DateTime('29 years ago')],
[new MaximumAge(30), new DateTimeImmutable('30 years ago')],
[new MaximumAge(30), new DateTimeImmutable('29 years ago')],
[new MaximumAge(30, 'Y-m-d'), new DateTime('30 years ago')],
[new MaximumAge(30, 'Y-m-d'), new DateTimeImmutable('30 years ago')],
[new MaximumAge(30, 'Y-m-d'), '30 years ago'],
[new MaximumAge(30, 'Y-m-d'), date('Y/m/d', strtotime('30 years ago'))],
[new MaximumAge(30), new DateTime('31 years ago')],
[new MaximumAge(30), new DateTimeImmutable('31 years ago')],
[new MaximumAge(30), '31 years ago'],
[new MaximumAge(30, 'Y-m-d'), date('Y-m-d', strtotime('31 years ago'))],
[new MaximumAge(30), 'invalid-input'],
[new MaximumAge(30), new stdClass()],
];
}
}

View file

@ -1,144 +0,0 @@
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use DateTime;
use PHPUnit\Framework\TestCase;
/**
* @group rule
* @covers \Respect\Validation\Rules\Age
* @covers \Respect\Validation\Exceptions\AgeException
*/
class AgeTest extends TestCase
{
/**
* @expectedException \Respect\Validation\Exceptions\ComponentException
* @expectedExceptionMessage An age interval must be provided
*/
public function testShouldThrowsExceptionWhenThereIsNoArgumentsOnConstructor(): void
{
new Age();
}
/**
* @expectedException \Respect\Validation\Exceptions\ComponentException
* @expectedExceptionMessage 20 cannot be greater than or equals to 10
*/
public function testShouldThrowsExceptionWhenMinimumAgeIsLessThenMaximumAge(): void
{
new Age(20, 10);
}
/**
* @expectedException \Respect\Validation\Exceptions\ComponentException
* @expectedExceptionMessage 20 cannot be greater than or equals to 20
*/
public function testShouldThrowsExceptionWhenMinimumAgeIsEqualsToMaximumAge(): void
{
new Age(20, 20);
}
public function providerForValidAge()
{
return [
[18, null, date('Y-m-d', strtotime('-18 years'))],
[18, null, date('Y-m-d', strtotime('-19 years'))],
[18, null, new DateTime('-18 years')],
[18, null, new DateTime('-19 years')],
[18, 50, date('Y-m-d', strtotime('-18 years'))],
[18, 50, date('Y-m-d', strtotime('-50 years'))],
[18, 50, new DateTime('-18 years')],
[18, 50, new DateTime('-50 years')],
[null, 50, date('Y-m-d', strtotime('-49 years'))],
[null, 50, date('Y-m-d', strtotime('-50 years'))],
[null, 50, new DateTime('-49 years')],
[null, 50, new DateTime('-50 years')],
];
}
/**
* @dataProvider providerForValidAge
*/
public function testShouldValidateValidAge($minAge, $maxAge, $input): void
{
$rule = new Age($minAge, $maxAge);
self::assertTrue($rule->validate($input));
}
public function providerForInvalidAge()
{
return [
[18, null, date('Y-m-d', strtotime('-17 years'))],
[18, null, new DateTime('-17 years')],
[18, 50, date('Y-m-d', strtotime('-17 years'))],
[18, 50, date('Y-m-d', strtotime('-51 years'))],
[18, 50, new DateTime('-17 years')],
[18, 50, new DateTime('-51 years')],
[null, 50, date('Y-m-d', strtotime('-51 years'))],
[null, 50, new DateTime('-51 years')],
];
}
/**
* @dataProvider providerForInvalidAge
*/
public function testShouldValidateInvalidAge($minAge, $maxAge, $input): void
{
$rule = new Age($minAge, $maxAge);
self::assertFalse($rule->validate($input));
}
/**
* @depends testShouldValidateInvalidAge
*
* @expectedException \Respect\Validation\Exceptions\AgeException
* @expectedExceptionMessage "today" must be lower than 18 years ago
*/
public function testShouldThrowsExceptionWhenMinimumAgeFails(): void
{
$rule = new Age(18);
$rule->assert('today');
}
/**
* @depends testShouldValidateInvalidAge
*
* @expectedException \Respect\Validation\Exceptions\AgeException
* @expectedExceptionMessage "51 years ago" must be greater than 50 years ago
*/
public function testShouldThrowsExceptionWhenMaximunAgeFails(): void
{
$rule = new Age(null, 50);
$rule->assert('51 years ago');
}
/**
* @depends testShouldValidateInvalidAge
*
* @expectedException \Respect\Validation\Exceptions\AgeException
* @expectedExceptionMessage "today" must be between 18 and 50 years ago
*/
public function testShouldThrowsExceptionWhenMinimunAndMaximunAgeFails(): void
{
$rule = new Age(18, 50);
$rule->assert('today');
}
}

View file

@ -0,0 +1,70 @@
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use DateTime;
use DateTimeImmutable;
use Respect\Validation\Test\RuleTestCase;
use stdClass;
use function date;
use function strtotime;
/**
* @group rule
*
* @covers \Respect\Validation\Rules\MinimumAge
* @covers \Respect\Validation\Rules\AbstractAge
*
* @author Henrique Moody <henriquemoody@gmail.com>
* @author Jean Pimentel <jeanfap@gmail.com>
* @author Kennedy Tedesco <kennedyt.tw@gmail.com>
*/
final class MinimumAgeTest extends RuleTestCase
{
/**
* {@inheritdoc}
*/
public function providerForValidInput(): array
{
return [
[new MinimumAge(18, 'Y-m-d'), date('Y-m-d', strtotime('18 years ago'))],
[new MinimumAge(18, 'Y-m-d'), date('Y-m-d', strtotime('19 years ago'))],
[new MinimumAge(18), '18 years ago'],
[new MinimumAge(18), '19 years ago'],
];
}
/**
* {@inheritdoc}
*/
public function providerForInvalidInput(): array
{
return [
[new MinimumAge(18), new DateTime('18 years ago')],
[new MinimumAge(18), new DateTimeImmutable('19 years ago')],
[new MinimumAge(18, 'Y-m-d'), new DateTime('100 years ago')],
[new MinimumAge(18, 'Y-m-d'), new DateTimeImmutable('18 years ago')],
[new MinimumAge(18, 'Y-m-d'), '100 years ago'],
[new MinimumAge(18, 'Y-m-d'), '18 years ago'],
[new MinimumAge(18, 'Y-m-d'), date('Y-m-d', strtotime('17 years ago'))],
[new MinimumAge(18), 'invalid-input'],
[new MinimumAge(18), new stdClass()],
[new MinimumAge(18, 'Y-m-d'), date('Y/m/d', strtotime('18 years ago'))],
[new MinimumAge(18, 'Y-m-d'), date('Y-m-d', strtotime('17 years ago'))],
[new MinimumAge(18), new DateTime('17 years ago')],
[new MinimumAge(18), new DateTimeImmutable('17 years ago')],
[new MinimumAge(18), '17 years ago'],
];
}
}

View file

@ -1,96 +0,0 @@
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use PHPUnit\Framework\TestCase;
/**
* @group rule
* @covers \Respect\Validation\Rules\MinimumAge
* @covers \Respect\Validation\Exceptions\MinimumAgeException
*/
class MininumAgeTest extends TestCase
{
/**
* @dataProvider providerForValidDateValidMinimumAge
*/
public function testValidMinimumAgeInsideBoundsShouldPass($age, $format, $input): void
{
$minimumAge = new MinimumAge($age, $format);
self::assertTrue($minimumAge->__invoke($input));
$minimumAge->assert($input);
$minimumAge->check($input);
}
/**
* @dataProvider providerForValidDateInvalidMinimumAge
* @expectedException \Respect\Validation\Exceptions\MinimumAgeException
*/
public function testInvalidMinimumAgeShouldThrowException($age, $format, $input): void
{
$minimumAge = new MinimumAge($age, $format);
self::assertFalse($minimumAge->__invoke($input));
$minimumAge->assert($input);
}
/**
* @dataProvider providerForInvalidDate
* @expectedException \Respect\Validation\Exceptions\MinimumAgeException
*/
public function testInvalidDateShouldNotPass($age, $format, $input): void
{
$minimumAge = new MinimumAge($age, $format);
self::assertFalse($minimumAge->__invoke($input));
$minimumAge->assert($input);
}
/**
* @expectedException \Respect\Validation\Exceptions\ComponentException
* @expectedExceptionMessage The age must be a integer value
*/
public function testShouldNotAcceptNonIntegerAgeOnConstructor(): void
{
new MinimumAge('L12');
}
public function providerForValidDateValidMinimumAge()
{
return [
[18, 'Y-m-d', ''],
[18, 'Y-m-d', '1969-07-20'],
[18, null, new \DateTime('1969-07-20')],
[18, 'Y-m-d', new \DateTime('1969-07-20')],
['18', 'Y-m-d', '1969-07-20'],
[18.0, 'Y-m-d', '1969-07-20'],
];
}
public function providerForValidDateInvalidMinimumAge()
{
return [
[18, 'Y-m-d', '2002-06-30'],
[18, null, new \DateTime('2002-06-30')],
[18, 'Y-m-d', new \DateTime('2002-06-30')],
];
}
public function providerForInvalidDate()
{
return [
[18, null, 'invalid-input'],
[18, null, new \stdClass()],
[18, 'y-m-d', '2002-06-30'],
];
}
}