Skip to content

Commit

Permalink
Merge pull request #340 from utopia-php/feat-past-date-validator
Browse files Browse the repository at this point in the history
adds past date validation
  • Loading branch information
abnegate authored Oct 18, 2023
2 parents 091e1a1 + 0801c6c commit e0b832d
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 8 deletions.
12 changes: 6 additions & 6 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 16 additions & 2 deletions src/Database/Validator/Datetime.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,16 @@ class Datetime extends Validator
*/
protected string $message = 'Date is not valid';

public function __construct()
/**
* @var bool
*/
protected bool $requireDateInFuture = false;

public function __construct(?bool $requireDateInFuture = null)
{
if (!is_null($requireDateInFuture)) {
$this->requireDateInFuture = $requireDateInFuture;
}
}

/**
Expand All @@ -37,7 +45,13 @@ public function isValid($value): bool
}

try {
new \DateTime($value);
$date = new \DateTime($value);
$now = new \DateTime();

if ($this->requireDateInFuture === true && $date < $now) {
$this->message = 'Date must be in the future';
return false;
}
} catch(\Exception $e) {
$this->message = $e->getMessage();
return false;
Expand Down
14 changes: 14 additions & 0 deletions tests/Database/Validator/DateTimeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,18 @@ public function testCreateDatetime(): void
*/
$this->assertEquals(false, $dateValidator->isValid("2022-13-04 11:31:52.680"));
}

public function testPastDateValidation(): void
{
$dateValidator = new DatetimeValidator(requireDateInFuture: true);

$this->assertEquals(false, $dateValidator->isValid(DateTime::addSeconds(new \DateTime(), -3)));
$this->assertEquals(true, $dateValidator->isValid(DateTime::addSeconds(new \DateTime(), 5)));


$dateValidator = new DatetimeValidator(requireDateInFuture: false);

$this->assertEquals(true, $dateValidator->isValid(DateTime::addSeconds(new \DateTime(), -3)));
$this->assertEquals(true, $dateValidator->isValid(DateTime::addSeconds(new \DateTime(), 5)));
}
}

0 comments on commit e0b832d

Please sign in to comment.