-
Notifications
You must be signed in to change notification settings - Fork 472
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
Refactor PrintfParametersRule #3247
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
<?php declare(strict_types = 1); | ||
|
||
namespace PHPStan\Rules\Functions; | ||
|
||
use Nette\Utils\Strings; | ||
use PHPStan\Php\PhpVersion; | ||
use function array_filter; | ||
use function count; | ||
use function max; | ||
use function sprintf; | ||
use function strlen; | ||
use const PREG_SET_ORDER; | ||
|
||
final class PrintfHelper | ||
{ | ||
|
||
public function __construct(private PhpVersion $phpVersion) | ||
{ | ||
} | ||
|
||
public function getPrintfPlaceholdersCount(string $format): int | ||
{ | ||
return $this->getPlaceholdersCount('(?:[bs%s]|l?[cdeEgfFGouxX])', $format); | ||
} | ||
|
||
public function getScanfPlaceholdersCount(string $format): int | ||
{ | ||
return $this->getPlaceholdersCount('(?:[cdDeEfinosuxX%s]|\[[^\]]+\])', $format); | ||
} | ||
|
||
private function getPlaceholdersCount(string $specifiersPattern, string $format): int | ||
{ | ||
$addSpecifier = ''; | ||
if ($this->phpVersion->supportsHhPrintfSpecifier()) { | ||
$addSpecifier .= 'hH'; | ||
} | ||
|
||
$specifiers = sprintf($specifiersPattern, $addSpecifier); | ||
|
||
$pattern = '~(?<before>%*)%(?:(?<position>\d+)\$)?[-+]?(?:[ 0]|(?:\'[^%]))?(?<width>\*)?-?\d*(?:\.(?:\d+|(?<precision>\*))?)?' . $specifiers . '~'; | ||
|
||
$matches = Strings::matchAll($format, $pattern, PREG_SET_ORDER); | ||
|
||
if (count($matches) === 0) { | ||
return 0; | ||
} | ||
|
||
$placeholders = array_filter($matches, static fn (array $match): bool => strlen($match['before']) % 2 === 0); | ||
|
||
if (count($placeholders) === 0) { | ||
return 0; | ||
} | ||
|
||
$maxPositionedNumber = 0; | ||
$maxOrdinaryNumber = 0; | ||
foreach ($placeholders as $placeholder) { | ||
if (isset($placeholder['width']) && $placeholder['width'] !== '') { | ||
$maxOrdinaryNumber++; | ||
} | ||
|
||
if (isset($placeholder['precision']) && $placeholder['precision'] !== '') { | ||
$maxOrdinaryNumber++; | ||
} | ||
|
||
if (isset($placeholder['position']) && $placeholder['position'] !== '') { | ||
$maxPositionedNumber = max((int) $placeholder['position'], $maxPositionedNumber); | ||
} else { | ||
$maxOrdinaryNumber++; | ||
} | ||
} | ||
|
||
return max($maxPositionedNumber, $maxOrdinaryNumber); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,30 +2,40 @@ | |
|
||
namespace PHPStan\Rules\Functions; | ||
|
||
use Nette\Utils\Strings; | ||
use PhpParser\Node; | ||
use PhpParser\Node\Expr\FuncCall; | ||
use PHPStan\Analyser\Scope; | ||
use PHPStan\Php\PhpVersion; | ||
use PHPStan\Reflection\ReflectionProvider; | ||
use PHPStan\Rules\Rule; | ||
use PHPStan\Rules\RuleErrorBuilder; | ||
use function array_filter; | ||
use function array_key_exists; | ||
use function count; | ||
use function in_array; | ||
use function max; | ||
use function sprintf; | ||
use function strlen; | ||
use function strtolower; | ||
use const PREG_SET_ORDER; | ||
|
||
/** | ||
* @implements Rule<Node\Expr\FuncCall> | ||
*/ | ||
class PrintfParametersRule implements Rule | ||
{ | ||
|
||
public function __construct(private PhpVersion $phpVersion) | ||
private const FORMAT_ARGUMENT_POSITIONS = [ | ||
'printf' => 0, | ||
'sprintf' => 0, | ||
'sscanf' => 1, | ||
'fscanf' => 1, | ||
]; | ||
private const MINIMUM_NUMBER_OF_ARGUMENTS = [ | ||
'printf' => 1, | ||
'sprintf' => 1, | ||
'sscanf' => 3, | ||
'fscanf' => 3, | ||
]; | ||
|
||
public function __construct( | ||
private PrintfHelper $printfHelper, | ||
private ReflectionProvider $reflectionProvider, | ||
) | ||
{ | ||
} | ||
|
||
|
@@ -40,25 +50,17 @@ public function processNode(Node $node, Scope $scope): array | |
return []; | ||
} | ||
|
||
$functionsArgumentPositions = [ | ||
'printf' => 0, | ||
'sprintf' => 0, | ||
'sscanf' => 1, | ||
'fscanf' => 1, | ||
]; | ||
$minimumNumberOfArguments = [ | ||
'printf' => 1, | ||
'sprintf' => 1, | ||
'sscanf' => 3, | ||
'fscanf' => 3, | ||
]; | ||
|
||
$name = strtolower((string) $node->name); | ||
if (!array_key_exists($name, $functionsArgumentPositions)) { | ||
if (!$this->reflectionProvider->hasFunction($node->name, $scope)) { | ||
return []; | ||
} | ||
|
||
$formatArgumentPosition = $functionsArgumentPositions[$name]; | ||
$functionReflection = $this->reflectionProvider->getFunction($node->name, $scope); | ||
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 was one of the few rules which did not validate the I guess its not strictly necessary because we are handling php-src native functions - I added it for consistency. |
||
$name = $functionReflection->getName(); | ||
if (!array_key_exists($name, self::FORMAT_ARGUMENT_POSITIONS)) { | ||
return []; | ||
} | ||
|
||
$formatArgumentPosition = self::FORMAT_ARGUMENT_POSITIONS[$name]; | ||
|
||
$args = $node->getArgs(); | ||
foreach ($args as $arg) { | ||
|
@@ -67,38 +69,44 @@ public function processNode(Node $node, Scope $scope): array | |
} | ||
} | ||
$argsCount = count($args); | ||
if ($argsCount < $minimumNumberOfArguments[$name]) { | ||
if ($argsCount < self::MINIMUM_NUMBER_OF_ARGUMENTS[$name]) { | ||
return []; // caught by CallToFunctionParametersRule | ||
} | ||
|
||
$formatArgType = $scope->getType($args[$formatArgumentPosition]->value); | ||
$placeHoldersCount = null; | ||
$maxPlaceHoldersCount = null; | ||
foreach ($formatArgType->getConstantStrings() as $formatString) { | ||
$format = $formatString->getValue(); | ||
$tempPlaceHoldersCount = $this->getPlaceholdersCount($name, $format); | ||
if ($placeHoldersCount === null) { | ||
$placeHoldersCount = $tempPlaceHoldersCount; | ||
} elseif ($tempPlaceHoldersCount > $placeHoldersCount) { | ||
$placeHoldersCount = $tempPlaceHoldersCount; | ||
|
||
if (in_array($name, ['sprintf', 'printf'], true)) { | ||
$tempPlaceHoldersCount = $this->printfHelper->getPrintfPlaceholdersCount($format); | ||
} else { | ||
$tempPlaceHoldersCount = $this->printfHelper->getScanfPlaceholdersCount($format); | ||
} | ||
|
||
if ($maxPlaceHoldersCount === null) { | ||
$maxPlaceHoldersCount = $tempPlaceHoldersCount; | ||
} elseif ($tempPlaceHoldersCount > $maxPlaceHoldersCount) { | ||
$maxPlaceHoldersCount = $tempPlaceHoldersCount; | ||
} | ||
} | ||
|
||
if ($placeHoldersCount === null) { | ||
if ($maxPlaceHoldersCount === null) { | ||
return []; | ||
} | ||
|
||
$argsCount -= $formatArgumentPosition; | ||
|
||
if ($argsCount !== $placeHoldersCount + 1) { | ||
if ($argsCount !== $maxPlaceHoldersCount + 1) { | ||
return [ | ||
RuleErrorBuilder::message(sprintf( | ||
sprintf( | ||
'%s, %s.', | ||
$placeHoldersCount === 1 ? 'Call to %s contains %d placeholder' : 'Call to %s contains %d placeholders', | ||
$maxPlaceHoldersCount === 1 ? 'Call to %s contains %d placeholder' : 'Call to %s contains %d placeholders', | ||
$argsCount - 1 === 1 ? '%d value given' : '%d values given', | ||
), | ||
$name, | ||
$placeHoldersCount, | ||
$maxPlaceHoldersCount, | ||
$argsCount - 1, | ||
))->identifier(sprintf('argument.%s', $name))->build(), | ||
]; | ||
|
@@ -107,49 +115,4 @@ public function processNode(Node $node, Scope $scope): array | |
return []; | ||
} | ||
|
||
private function getPlaceholdersCount(string $functionName, string $format): int | ||
{ | ||
$specifiers = in_array($functionName, ['sprintf', 'printf'], true) ? '(?:[bs%s]|l?[cdeEgfFGouxX])' : '(?:[cdDeEfinosuxX%s]|\[[^\]]+\])'; | ||
$addSpecifier = ''; | ||
if ($this->phpVersion->supportsHhPrintfSpecifier()) { | ||
$addSpecifier .= 'hH'; | ||
} | ||
|
||
$specifiers = sprintf($specifiers, $addSpecifier); | ||
|
||
$pattern = '~(?<before>%*)%(?:(?<position>\d+)\$)?[-+]?(?:[ 0]|(?:\'[^%]))?(?<width>\*)?-?\d*(?:\.(?:\d+|(?<precision>\*))?)?' . $specifiers . '~'; | ||
|
||
$matches = Strings::matchAll($format, $pattern, PREG_SET_ORDER); | ||
|
||
if (count($matches) === 0) { | ||
return 0; | ||
} | ||
|
||
$placeholders = array_filter($matches, static fn (array $match): bool => strlen($match['before']) % 2 === 0); | ||
|
||
if (count($placeholders) === 0) { | ||
return 0; | ||
} | ||
|
||
$maxPositionedNumber = 0; | ||
$maxOrdinaryNumber = 0; | ||
foreach ($placeholders as $placeholder) { | ||
if (isset($placeholder['width']) && $placeholder['width'] !== '') { | ||
$maxOrdinaryNumber++; | ||
} | ||
|
||
if (isset($placeholder['precision']) && $placeholder['precision'] !== '') { | ||
$maxOrdinaryNumber++; | ||
} | ||
|
||
if (isset($placeholder['position']) && $placeholder['position'] !== '') { | ||
$maxPositionedNumber = max((int) $placeholder['position'], $maxPositionedNumber); | ||
} else { | ||
$maxOrdinaryNumber++; | ||
} | ||
} | ||
|
||
return max($maxPositionedNumber, $maxOrdinaryNumber); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I need this use-cases separated because I only need the
getPrintfPlaceholdersCount
inPrintfArrayParametersRule