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

Support of printf with dynamic width #2543

Merged
merged 1 commit into from
Jul 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/Rules/Functions/PrintfParametersRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ private function getPlaceholdersCount(string $functionName, string $format): int

$specifiers = sprintf($specifiers, $addSpecifier);

$pattern = '~(?<before>%*)%(?:(?<position>\d+)\$)?[-+]?(?:[ 0]|(?:\'[^%]))?-?\d*(?:\.\d*)?' . $specifiers . '~';
$pattern = '~(?<before>%*)%(?:(?<position>\d+)\$)?[-+]?(?:(?:[ 0]|(?:\'[^%]))(?<width>\*)?)?-?\d*(?:\.\d*)?' . $specifiers . '~';

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking at this regex, I see the precision doesn't allow for a * either.

Sorry for not testing that case before opening the issue 😖

From the doc:

Note: If the period is specified without an explicit value for precision, 0 is assumed. If * is used, the precision is supplied as an additional integer value preceding the one formatted by the specifier.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@fmarchalemisys Please open new issue.


$matches = Strings::matchAll($format, $pattern, PREG_SET_ORDER);

Expand All @@ -133,6 +133,10 @@ private function getPlaceholdersCount(string $functionName, string $format): int
$maxPositionedNumber = 0;
$maxOrdinaryNumber = 0;
foreach ($placeholders as $placeholder) {
if (isset($placeholder['width'])) {
$maxOrdinaryNumber++;
}

if (isset($placeholder['position']) && $placeholder['position'] !== '') {
$maxPositionedNumber = max((int) $placeholder['position'], $maxPositionedNumber);
} else {
Expand Down
4 changes: 4 additions & 0 deletions tests/PHPStan/Rules/Functions/data/printf.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,7 @@
sprintf('%lu', 1); // ok
sprintf('%lx', 1); // ok
sprintf('%lX', 1); // ok

printf('%0*d', 5, 1); // ok
printf("%'x*d", 5, 1); // ok
printf("%0*d %'x*d", 5, 1, 4, 3); // ok
Loading