Skip to content

Commit

Permalink
Support of printf with dynamic precision (and improved support of dyn…
Browse files Browse the repository at this point in the history
…amic width)
  • Loading branch information
kukulich authored and ondrejmirtes committed Jul 24, 2023
1 parent 655e028 commit 91c8b5f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
8 changes: 6 additions & 2 deletions 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]|(?:\'[^%]))(?<width>\*)?)?-?\d*(?:\.\d*)?' . $specifiers . '~';
$pattern = '~(?<before>%*)%(?:(?<position>\d+)\$)?[-+]?(?:[ 0]|(?:\'[^%]))?(?<width>\*)?-?\d*(?:\.(?:\d+|(?<precision>\*))?)?' . $specifiers . '~';

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

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

if (isset($placeholder['precision']) && $placeholder['precision'] !== '') {
$maxOrdinaryNumber++;
}

Expand Down
5 changes: 5 additions & 0 deletions tests/PHPStan/Rules/Functions/data/printf.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,8 @@
printf('%0*d', 5, 1); // ok
printf("%'x*d", 5, 1); // ok
printf("%0*d %'x*d", 5, 1, 4, 3); // ok

printf('%6.*f', 2, 1); // ok
printf('%0*.*f', 6, 2, 1); // ok
printf('%*.*f', 6, 2, 1); // ok
printf('%*.*f %*.*f', 6, 2, 1, 5, 3, 2); // ok

0 comments on commit 91c8b5f

Please sign in to comment.