-
Notifications
You must be signed in to change notification settings - Fork 773
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
Open
gvieiragoulart
wants to merge
9
commits into
Respect:main
Choose a base branch
from
gvieiragoulart:rule/dateTimeDiff
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Rule/date time diff #1463
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
9e631a8
Create "DateTimeDiff" rule
henriquemoody b0d2e88
type params, delete unnecessary code
gvieiragoulart 85d5b9e
include not to pass test
gvieiragoulart 205a0b7
test days with difference of months
gvieiragoulart 4ebf053
cange the validation to be and DateInterval type and add "d" type
gvieiragoulart 906f722
write md docs
gvieiragoulart caee0e4
improve tests
gvieiragoulart 5ea05c9
fix phpcs
gvieiragoulart 94d9d46
fix phpstan
gvieiragoulart File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,153 @@ | ||
<?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 | ||
*/ | ||
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 | ||
{ | ||
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', | ||
'h' => 'hours', | ||
'i' => 'minutes', | ||
's' => 'seconds', | ||
'f' => 'microseconds', | ||
default => 'unknown type', | ||
}; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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?