-
Notifications
You must be signed in to change notification settings - Fork 772
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Rule/date time diff #1463
base: main
Are you sure you want to change the base?
Rule/date time diff #1463
Changes from 7 commits
9e631a8
b0d2e88
85d5b9e
205a0b7
4ebf053
906f722
caee0e4
5ea05c9
94d9d46
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
# DateTimeDiff | ||
|
||
- `DateTimeDiff(Validatable $rule)` | ||
- `DateTimeDiff(Validatable $rule, string $type)` | ||
- `DateTimeDiff(Validatable $rule, string $type, string $format)` | ||
|
||
Validates the difference of date/time against a specific rule. | ||
|
||
The `$format` argument should follow PHP's [date()][] function. When the `$format` is not given, this rule accepts | ||
[Supported Date and Time Formats][] by PHP (see [strtotime()][]). | ||
|
||
The `$type` argument should follow PHP's [DateInterval] properties. When the `$type` is not given, its default value is `y`. | ||
|
||
```php | ||
v::dateTimeDiff(v::equal(7))->validate('7 years ago - 1 minute'); // true | ||
v::dateTimeDiff(v::equal(7))->validate('7 years ago + 1 minute'); // false | ||
|
||
v::dateTimeDiff(v::greaterThan(18), 'y', 'd/m/Y')->validate('09/12/1990'); // true | ||
v::dateTimeDiff(v::greaterThan(18), 'y', 'd/m/Y')->validate('09/12/2023'); // false | ||
|
||
v::dateTimeDiff(v::between(1, 18), 'm')->validate('5 months ago'); // true | ||
``` | ||
|
||
The supported types are: | ||
|
||
* `years` as `y` | ||
* `months` as `m` | ||
* `days` as `days` and `d` | ||
* `hours` as `h` | ||
* `minutes` as `i` | ||
* `seconds` as `s` | ||
* `microseconds` as `f` | ||
|
||
Difference between `d` and `days` | ||
|
||
`d` (days): Represents the difference in days within the same month or year. For example, if the difference between two dates is 1 month and 10 days, the value of d will be 10. | ||
|
||
`days` (full days): Represents the total difference in days between two dates, regardless of months or years. For example, if the difference between two dates is 1 month and 10 days, the value of days will be the total number of days between these dates. | ||
|
||
## Categorization | ||
|
||
- Date and Time | ||
|
||
## Changelog | ||
|
||
| Version | Description | | ||
| ------: |--------------------------------------------| | ||
| 3.0.0 | Created from `Age`, `MinAge`, and `MaxAge` | | ||
|
||
*** | ||
See also: | ||
|
||
- [Date](Date.md) | ||
- [DateTime](DateTime.md) | ||
- [Max](Max.md) | ||
- [Min](Min.md) | ||
- [Time](Time.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 | ||
[DateInterval]: https://www.php.net/manual/en/class.dateinterval.php |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
<?php | ||
|
||
/* | ||
* Copyright (c) Alexandre Gomes Gaigalas <[email protected]> | ||
* SPDX-License-Identifier: MIT | ||
*/ | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Respect\Validation\Rules; | ||
|
||
use DateTimeImmutable; | ||
use DateTimeInterface; | ||
use Respect\Validation\Exceptions\InvalidRuleConstructorException; | ||
use Respect\Validation\Helpers\CanBindEvaluateRule; | ||
use Respect\Validation\Helpers\CanExtractRules; | ||
use Respect\Validation\Helpers\CanValidateDateTime; | ||
use Respect\Validation\Message\Template; | ||
use Respect\Validation\Result; | ||
use Respect\Validation\Rules\Core\Standard; | ||
use Respect\Validation\Validatable; | ||
|
||
use function is_scalar; | ||
|
||
#[Template( | ||
'The number of {{type|raw}} between {{now|raw}} and', | ||
'The number of {{type|raw}} between {{now|raw}} and', | ||
)] | ||
final class DateTimeDiff extends Standard | ||
{ | ||
use CanBindEvaluateRule; | ||
use CanValidateDateTime; | ||
use CanExtractRules; | ||
|
||
private readonly Validatable $rule; | ||
|
||
/** | ||
* @param string $type DateInterval format examples: | ||
* - 'y': years | ||
* - 'm': months | ||
* - 'd': days (within the same month or year) | ||
* - 'days': full days (total difference in days) | ||
* - 'h': hours | ||
* - 'i': minutes | ||
* - 's': seconds | ||
* - 'f': microseconds | ||
* @param DateTimeImmutable|null $now The value that will be compared to the input | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm a against adding documentation to the code like that, I think the name of the parameter should be pretty obvious for what it does, otherwise we should do that for everything. I understand that it can be useful to add some documentation here and there, but for this specific method, I would rather not have it. |
||
*/ | ||
public function __construct( | ||
Validatable $rule, | ||
private readonly string $type = 'y', | ||
private readonly ?string $format = null, | ||
private readonly ?DateTimeImmutable $now = null, | ||
) { | ||
if (!$this->isDateIntervalType($this->type)) { | ||
throw new InvalidRuleConstructorException( | ||
'"%s" is not a valid type of age (Available: %s)', | ||
$this->type, | ||
['y', 'm', 'd', 'days', 'h', 'i', 's', 'f'] | ||
); | ||
} | ||
$this->rule = $this->extractSiblingSuitableRule( | ||
$rule, | ||
new InvalidRuleConstructorException('DateTimeDiff must contain exactly one rule') | ||
); | ||
} | ||
|
||
public function evaluate(mixed $input): Result | ||
{ | ||
$compareTo = $this->createDateTimeObject($input); | ||
if ($compareTo === null) { | ||
return Result::failed($input, $this); | ||
} | ||
|
||
$dateTimeResult = $this->bindEvaluate( | ||
binded: new DateTime($this->format), | ||
binder: $this, | ||
input: $input | ||
); | ||
if (!$dateTimeResult->isValid) { | ||
return $dateTimeResult; | ||
} | ||
|
||
$now = $this->now ?? new DateTimeImmutable(); | ||
|
||
$nextSibling = $this->rule | ||
->evaluate($this->comparisonValue($now, $compareTo)) | ||
->withNameIfMissing($input instanceof DateTimeInterface ? $input->format('c') : $input); | ||
|
||
$parameters = [ | ||
'type' => $this->getTranslatedType($this->type), | ||
'now' => $this->nowParameter($now) | ||
]; | ||
|
||
return (new Result($nextSibling->isValid, $input, $this, $parameters))->withNextSibling($nextSibling); | ||
} | ||
|
||
private function comparisonValue(DateTimeInterface $now, DateTimeInterface $compareTo): int|float | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not sure if that's correct, because |
||
{ | ||
return $compareTo->diff($now)->{$this->type}; | ||
} | ||
|
||
private function nowParameter(DateTimeInterface $now): string | ||
{ | ||
if ($this->format === null && $this->now === null) { | ||
return 'now'; | ||
} | ||
|
||
if ($this->format === null) { | ||
return $now->format('Y-m-d H:i:s.u'); | ||
} | ||
|
||
return $now->format($this->format); | ||
} | ||
|
||
private function createDateTimeObject(mixed $input): ?DateTimeInterface | ||
{ | ||
if ($input instanceof DateTimeInterface) { | ||
return $input; | ||
} | ||
|
||
if (!is_scalar($input)) { | ||
return null; | ||
} | ||
|
||
if ($this->format === null) { | ||
return new DateTimeImmutable((string) $input); | ||
} | ||
|
||
$format = $this->getExceptionalFormats()[$this->format] ?? $this->format; | ||
$dateTime = DateTimeImmutable::createFromFormat($format, (string) $input); | ||
if ($dateTime === false) { | ||
return null; | ||
} | ||
|
||
return $dateTime; | ||
} | ||
|
||
private function getTranslatedType(string $type): string | ||
{ | ||
return match ($type) { | ||
'y' => 'years', | ||
'm' => 'months', | ||
'd' => 'days', | ||
'days' => 'full days', | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Very nice catch! |
||
'h' => 'hours', | ||
'i' => 'minutes', | ||
's' => 'seconds', | ||
'f' => 'microseconds', | ||
}; | ||
} | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If we are going to use this, I believe that we can improve to a Enum file. I didn't create because the project don't have any |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I know this seems weird, but i wanted to use those DateInterval vars. what do you guys think about it? How do we can improve this validation?