Skip to content

Commit

Permalink
Support of printf with dynamic width
Browse files Browse the repository at this point in the history
  • Loading branch information
kukulich committed Jul 24, 2023
1 parent 40cadaa commit 02d35be
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
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 . '~';

$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

0 comments on commit 02d35be

Please sign in to comment.