Skip to content
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

hasFormat false positive #2185

Closed
djereg opened this issue Sep 9, 2020 · 2 comments
Closed

hasFormat false positive #2185

djereg opened this issue Sep 9, 2020 · 2 comments
Assignees
Labels
Milestone

Comments

@djereg
Copy link

djereg commented Sep 9, 2020

Hello,

I encountered an issue with the following code:

echo Carbon::hasFormat('2020-09-09', 'Y.m.d');

Carbon version: 2.39.1

PHP version: 7.4.9

I expected to get:

false

But I actually get:

true

For this format, the generated regex is ([1-9]?[0-9]{4}).(1[012]|0[1-9]).(3[01]|[12][0-9]|0[1-9]) where the problem is the . between the parts, instead of \., which will pass everything on that places.

Carbon::hasFormat('2020-09-09', 'Y.m.d'); // true
Carbon::hasFormat('2020.09.09', 'Y.m.d'); // true
Carbon::hasFormat('2020*09*09', 'Y.m.d'); // true
Carbon::hasFormat('2020k09d09', 'Y.m.d'); // true

public static function hasFormat($date, $format)
{
// createFromFormat() is known to handle edge cases silently.
// E.g. "1975-5-1" (Y-n-j) will still be parsed correctly when "Y-m-d" is supplied as the format.
// To ensure we're really testing against our desired format, perform an additional regex validation.
// Preg quote, but remove escaped backslashes since we'll deal with escaped characters in the format string.
$quotedFormat = str_replace('\\\\', '\\', preg_quote($format, '/'));
// Build the regex string
$regex = '';
for ($i = 0; $i < strlen($quotedFormat); ++$i) {
// Backslash – the next character does not represent a date token so add it on as-is and continue.
// We're doing an extra ++$i here to increment the loop by 2.
if ($quotedFormat[$i] === '\\') {
$char = $quotedFormat[++$i];
$regex .= $char === '\\' ? '\\\\' : $char;
continue;
}
$regex .= strtr($quotedFormat[$i], static::$regexFormats);
}
$regex = preg_replace('#(?<!\\\\)((?:\\\\{2})*)/#', '$1\\/', $regex);
return (bool) @preg_match('/^'.$regex.'$/', $date);
}

Thanks!

@kylekatarnls kylekatarnls added this to the 2.39.2 milestone Sep 9, 2020
@kylekatarnls kylekatarnls self-assigned this Sep 9, 2020
@kylekatarnls
Copy link
Collaborator

I confirm this regressed from 2.39.0 to 2.39.1.

@kylekatarnls
Copy link
Collaborator

Fixed in 2.39.2. Thanks for the report.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants