-
-
Notifications
You must be signed in to change notification settings - Fork 9.7k
[Validator] Support \DateInterval in comparison constraints #33401
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
Changes from all commits
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 |
---|---|---|
|
@@ -31,6 +31,12 @@ abstract class ConstraintValidator implements ConstraintValidatorInterface | |
*/ | ||
const OBJECT_TO_STRING = 2; | ||
|
||
/** | ||
* Whether to format {@link \DateInterval} objects as human readable strings | ||
* eg: 6 hours, 1 minute and 2 seconds. | ||
*/ | ||
const PRETTY_DATE_INTERVAL = 4; | ||
|
||
/** | ||
* @var ExecutionContextInterface | ||
*/ | ||
|
@@ -98,6 +104,37 @@ protected function formatValue($value, int $format = 0) | |
return $value->format('Y-m-d H:i:s'); | ||
} | ||
|
||
if (($format & self::PRETTY_DATE_INTERVAL) && $value instanceof \DateInterval) { | ||
$formattedValueParts = []; | ||
foreach ([ | ||
'y' => 'year', | ||
'm' => 'month', | ||
'd' => 'day', | ||
'h' => 'hour', | ||
'i' => 'minute', | ||
's' => 'second', | ||
'f' => 'microsecond', | ||
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. this formatting logic is English-only, which looks bad. 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. As we did for dates just above, the format is hardcoded here except in this case there are words. |
||
] as $p => $label) { | ||
if (!$formattedValue = $value->format('%'.$p)) { | ||
continue; | ||
} | ||
|
||
if ($formattedValue > 1) { | ||
$label .= 's'; | ||
} | ||
|
||
$formattedValueParts[] = $formattedValue.' '.$label; | ||
} | ||
|
||
if (!$formattedValueParts) { | ||
return '0'; | ||
} | ||
|
||
$lastFormattedValuePart = array_pop($formattedValueParts); | ||
|
||
return $value->format('%r').(!$formattedValueParts ? $lastFormattedValuePart : implode(', ', $formattedValueParts).' and '.$lastFormattedValuePart); | ||
fancyweb marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
if (\is_object($value)) { | ||
if (($format & self::OBJECT_TO_STRING) && method_exists($value, '__toString')) { | ||
return $value->__toString(); | ||
|
Uh oh!
There was an error while loading. Please reload this page.