Skip to content
Open
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
30 changes: 20 additions & 10 deletions src/Rules/Functions/PrintfHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
use Nette\Utils\Strings;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Php\PhpVersion;
use ValueError;
use function array_filter;
use function array_keys;
use function count;
use function in_array;
use function max;
use function sprintf;
use function sscanf;
use function strlen;
use const PREG_SET_ORDER;

Expand All @@ -26,24 +28,36 @@ public function __construct(private PhpVersion $phpVersion)

public function getPrintfPlaceholdersCount(string $format): ?int
{
return $this->getPlaceholdersCount(self::PRINTF_SPECIFIER_PATTERN, $format, false);
return $this->getPlaceholdersCount(self::PRINTF_SPECIFIER_PATTERN, $format);
}

/** @phpstan-return array<int, non-empty-list<PrintfPlaceholder>> parameter index => placeholders */
public function getPrintfPlaceholders(string $format): ?array
{
return $this->parsePlaceholders(self::PRINTF_SPECIFIER_PATTERN, $format, false);
return $this->parsePlaceholders(self::PRINTF_SPECIFIER_PATTERN, $format);
}

public function getScanfPlaceholdersCount(string $format): ?int
{
return $this->getPlaceholdersCount('(?<specifier>[cdDeEfinosuxX%s]|\[[^\]]+\])', $format, true);
if ($this->phpVersion->throwsValueErrorForInternalFunctions()) {
try {
$result = sscanf('', '%*n' . $format);
} catch (ValueError) {
return null;
}
} else {
$result = @sscanf('', '%*n' . $format);
}
if ($result === null) {
return null;
}
return count($result);
}

/**
* @phpstan-return array<int, non-empty-list<PrintfPlaceholder>>|null parameter index => placeholders
*/
private function parsePlaceholders(string $specifiersPattern, string $format, bool $isScanf): ?array
private function parsePlaceholders(string $specifiersPattern, string $format): ?array
{
$addSpecifier = '';
if ($this->phpVersion->supportsHhPrintfSpecifier()) {
Expand Down Expand Up @@ -72,10 +86,6 @@ private function parsePlaceholders(string $specifiersPattern, string $format, bo
$showValueSuffix = false;

if (isset($placeholder['width']) && $placeholder['width'] !== '') {
if ($isScanf) {
// In scanf, * means assignment suppression - skip this placeholder entirely
continue;
}
$parsedPlaceholders[] = new PrintfPlaceholder(
sprintf('"%s" (width)', $placeholder[0]),
$parameterIdx++,
Expand Down Expand Up @@ -136,9 +146,9 @@ private function getAcceptingTypeBySpecifier(string $specifier): string
return 'mixed';
}

private function getPlaceholdersCount(string $specifiersPattern, string $format, bool $isScanf): ?int
private function getPlaceholdersCount(string $specifiersPattern, string $format): ?int
{
$placeholdersMap = $this->parsePlaceholders($specifiersPattern, $format, $isScanf);
$placeholdersMap = $this->parsePlaceholders($specifiersPattern, $format);
if ($placeholdersMap === null) {
return null;
}
Expand Down
164 changes: 164 additions & 0 deletions tests/PHPStan/Rules/Functions/PrintfHelperTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Functions;

use Generator;
use IteratorAggregate;
use Override;
use PHPStan\Php\PhpVersion;
use PHPStan\Testing\PHPStanTestCase;
use PHPUnit\Framework\Attributes\CoversMethod;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\RequiresPhp;
use Throwable;
use ValueError;
use function max;
use function min;
use function range;
use function sprintf;
use function sscanf;
use function strlen;
use const PHP_INT_MAX;
use const PHP_VERSION_ID;

#[CoversMethod(PrintfHelper::class, 'getScanfPlaceholdersCount')]

Check failure on line 24 in tests/PHPStan/Rules/Functions/PrintfHelperTest.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.0, ubuntu-latest)

Attribute class PHPUnit\Framework\Attributes\CoversMethod does not exist.

Check failure on line 24 in tests/PHPStan/Rules/Functions/PrintfHelperTest.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.1, ubuntu-latest)

Attribute class PHPUnit\Framework\Attributes\CoversMethod does not exist.

Check failure on line 24 in tests/PHPStan/Rules/Functions/PrintfHelperTest.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.0, windows-latest)

Attribute class PHPUnit\Framework\Attributes\CoversMethod does not exist.

Check failure on line 24 in tests/PHPStan/Rules/Functions/PrintfHelperTest.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.1, windows-latest)

Attribute class PHPUnit\Framework\Attributes\CoversMethod does not exist.
class PrintfHelperTest extends PHPStanTestCase
{

private PrintfHelper $printf;

#[Override]
protected function setUp(): void
{
$this->printf = $this->getPhpVersionIdAwareHelper(PHP_VERSION_ID);
}

#[RequiresPhp('< 8.0.0')]
public function testReturnsNullForInvalidPatternOnLegacyPhpVersion(): void
{
$this->assertNull($this->printf->getScanfPlaceholdersCount('%a'));
}

#[RequiresPhp('>= 8.0.0')]
public function testReturnsNullForInvalidPatternOnPhp8(): void
{
$this->assertNull($this->printf->getScanfPlaceholdersCount('%a'));
}

#[RequiresPhp('>= 8.0.0')]
#[DataProvider('dataLegacyVersionIds')]
public function testLegacyVersionStillThrowsValueErrorOnPhp8(int $versionId): void
{
$helper = $this->getPhpVersionIdAwareHelper($versionId);
$this->expectException(ValueError::class);
$this->expectExceptionMessage('Bad scan conversion character "a"');
$helper->getScanfPlaceholdersCount('%a');
$this->fail('check your phpunit');
}

private function getPhpVersionIdAwareHelper(int $versionId): PrintfHelper
{
return new PrintfHelper($this->getPhpVersion($versionId));
}

private function getPhpVersion(int $versionId): PhpVersion
{
return new PhpVersion($versionId);
}

public static function dataLegacyVersionIds(): Generator
{
static $line;
$line ??= new class () implements IteratorAggregate {

/** @var array<int, array<int, int>> */
private readonly array $base;

/** @var array<int, int> */
private readonly array $major;

/** @var array<int, int> */
private readonly array $release;

/**
* @return Generator<int,array{int, int, int}, void, void>
*/
#[Override]
public function getIterator(): Generator
{
foreach ($this->major as $major) {
$minors = $this->base[$major];
foreach ($minors as $minor) {
foreach ($this->release as $release) {
yield [$major, $minor, $release];
}
}
}
}

public function __construct()
{
$this->major = range(4, 9);
$this->release = range(0, 48);
/**
* @var array<int, array<int, int>>
*/
$base = [
4 => [3, 4],
5 => range(0, 6),
6 => [],
7 => range(0, 4),
];
foreach ($this->major as $major) {
if (isset($base[$major])) {
continue;
}

// 8: 0...48, 9: 0...36, 10: 0...24, 11...: 0...12
$base[$major] = range(0, max(1, -1 * ($major + -12)) * 12);
}
$this->base = $base;
}

};

$errored = 0;
$skipped = 0;
$matched = 0;
$expectSkipped = 4214;
$expectMatched = 686;

foreach ($line as [$major, $minor, $release]) {
$triplet = [max(1, $major), max(0, min(99, $minor)), max(0, min(99, $release))];
$strval = sprintf('%d%02d%02d', ...$triplet);
$ret = sscanf($strval, '%d%n', $intval, $len);
self::assertSame(2, $ret, 'check your base');
self::assertIsInt($intval, 'check %d specifier php manual and sscanf sources');
self::assertSame(strlen($strval), $len, 'check string: ' . $strval . ' which is of len ' . strlen($strval));
self::assertNotSame(PHP_INT_MAX, $intval, 'IntMax ceiling hit');
self::assertGreaterThan(0, $intval, 'UnsignedInt floor hit');
$self ??= new PrintfHelperTest(__METHOD__);
try {
$version = $self->getPhpVersion($intval);
} catch (Throwable) {
$errored++;
continue;
}
$throws = $version->throwsValueErrorForInternalFunctions();
if ($throws) {
$skipped++;
continue;
}
$matched++;
$i ??= 0;
$i++;
$case = sprintf('case #%02d php %d.%d.%d [version-id %s]', $i, $major, $minor, $release, $strval);
yield $case => [$intval];
}

self::assertSame(0, $errored);
self::assertSame($expectSkipped, $skipped);
self::assertSame($expectMatched, $matched);
}

}
8 changes: 8 additions & 0 deletions tests/PHPStan/Rules/Functions/PrintfParametersRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,14 @@ public function testFile(): void
'Call to sprintf contains 2 placeholders, 1 value given.',
29,
],
[
'Call to sscanf contains an invalid placeholder.',
38,
],
[
'Call to fscanf contains an invalid placeholder.',
39,
],
[
'Call to sprintf contains 2 placeholders, 1 value given.',
45,
Expand Down
4 changes: 2 additions & 2 deletions tests/PHPStan/Rules/Functions/data/printf.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@
sscanf($str, "%20[^abcde]a%d", $string, $number); // ok
printf("%.E", 3.14159); // ok
sprintf("%.E", 3.14159); // ok
sscanf($str, '%.E', $number); // ok
fscanf($str, '%.E', $number); // ok
sscanf($str, '%.E', $number); // bad scan conversion character '.'
fscanf($resource, '%.E', $number); // bad scan conversion character '.'
sscanf($str, '%[A-Z]%d', $char, $number); // ok
sprintf('%s %s %s', ...[1]); // do not detect unpacked arguments
sprintf('%s %s %s', ...[1, 2, 3]); // ok
Expand Down
Loading