diff --git a/config/rules.neon b/config/rules.neon index c91aefad..7196099b 100644 --- a/config/rules.neon +++ b/config/rules.neon @@ -99,3 +99,9 @@ services: - 'mysqli::execute_query#0' - 'Doctrine\DBAL\Connection::query#0' # deprecated in doctrine - 'Doctrine\DBAL\Connection::exec#0' # deprecated in doctrine + + - + class: staabm\PHPStanDba\Rules\MysqliFetchColumnRule + tags: [phpstan.rules.rule] + arguments: + reportMaybes: %reportMaybes% diff --git a/src/Extensions/MysqliResultDynamicReturnTypeExtension.php b/src/Extensions/MysqliResultDynamicReturnTypeExtension.php index 789520d5..57c0c70b 100644 --- a/src/Extensions/MysqliResultDynamicReturnTypeExtension.php +++ b/src/Extensions/MysqliResultDynamicReturnTypeExtension.php @@ -17,8 +17,6 @@ use PHPStan\ShouldNotHappenException; use PHPStan\Type\Accessory\AccessoryArrayListType; use PHPStan\Type\ArrayType; -use PHPStan\Type\Constant\ConstantArrayType; -use PHPStan\Type\Constant\ConstantArrayTypeBuilder; use PHPStan\Type\Constant\ConstantBooleanType; use PHPStan\Type\Constant\ConstantIntegerType; use PHPStan\Type\DynamicFunctionReturnTypeExtension; @@ -35,13 +33,6 @@ final class MysqliResultDynamicReturnTypeExtension implements DynamicFunctionReturnTypeExtension, DynamicMethodReturnTypeExtension { - // same-value replacements for MYSQLI_ASSOC, MYSQLI_NUM, MYSQLI_BOTH constants in mysqli extension - private const MYSQLI_ASSOC = 1; - - private const MYSQLI_NUM = 2; - - private const MYSQLI_BOTH = 3; - private ReflectionProvider $reflectionProvider; public function __construct(ReflectionProvider $reflectionProvider) @@ -70,7 +61,7 @@ public function fetchAll(array $modes, Type $rowType): ?Type { $rows = []; foreach ($modes as $mode) { - $modeRowType = $this->getRowTypeForMode($rowType, $mode); + $modeRowType = MysqliResultObjectType::getRowTypeForMode($rowType, $mode); if ($modeRowType === null) { return null; } @@ -215,7 +206,7 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection, return $this->fetchAll($modes, $rowType); } - $numericRowType = $this->getRowTypeForMode($rowType, self::MYSQLI_NUM); + $numericRowType = MysqliResultObjectType::getRowTypeForMode($rowType); if ($numericRowType === null) { return null; } @@ -350,7 +341,7 @@ public function getTypeFromMethodCall(MethodReflection $methodReflection, Method return $this->fetchAll($modes, $rowType); } - $numericRowType = $this->getRowTypeForMode($rowType, self::MYSQLI_NUM); + $numericRowType = MysqliResultObjectType::getRowTypeForMode($rowType); if ($numericRowType === null) { return null; } @@ -425,42 +416,4 @@ private function getModes(Type $modeType): ?array return $modes; } - - private function getRowTypeForMode(Type $rowType, int $mode): ?Type - { - if (! \in_array($mode, [self::MYSQLI_NUM, self::MYSQLI_ASSOC, self::MYSQLI_BOTH], true)) { - return null; - } - - $rowTypes = []; - foreach ($rowType->getConstantArrays() as $arrayType) { - $rowTypes[] = $this->convertRowType($arrayType, $mode); - } - - if (count($rowTypes) === 0) { - return null; - } - - return TypeCombinator::union(...$rowTypes); - } - - private function convertRowType(ConstantArrayType $rowType, int $mode): Type - { - $builder = ConstantArrayTypeBuilder::createEmpty(); - $numericIndex = 0; - - foreach ($rowType->getKeyTypes() as $index => $keyType) { - $valueType = $rowType->getValueTypes()[$index]; - if ($mode === self::MYSQLI_ASSOC || $mode === self::MYSQLI_BOTH) { - $builder->setOffsetValueType($keyType, $valueType); - } - - if ($mode === self::MYSQLI_NUM || $mode === self::MYSQLI_BOTH) { - $builder->setOffsetValueType(new ConstantIntegerType($numericIndex), $valueType); - $numericIndex++; - } - } - - return $builder->getArray(); - } } diff --git a/src/MysqliReflection/MysqliResultObjectType.php b/src/MysqliReflection/MysqliResultObjectType.php index 707b692e..5abcd977 100644 --- a/src/MysqliReflection/MysqliResultObjectType.php +++ b/src/MysqliReflection/MysqliResultObjectType.php @@ -5,12 +5,22 @@ namespace staabm\PHPStanDba\MysqliReflection; use PHPStan\ShouldNotHappenException; +use PHPStan\Type\Constant\ConstantArrayTypeBuilder; +use PHPStan\Type\Constant\ConstantIntegerType; use PHPStan\Type\IsSuperTypeOfResult; use PHPStan\Type\ObjectType; use PHPStan\Type\Type; +use PHPStan\Type\TypeCombinator; final class MysqliResultObjectType extends ObjectType { + // same-value replacements for MYSQLI_ASSOC, MYSQLI_NUM, MYSQLI_BOTH constants in mysqli extension + private const MYSQLI_ASSOC = 1; + + private const MYSQLI_NUM = 2; + + private const MYSQLI_BOTH = 3; + private ?Type $rowType = null; public static function newWithRowType(Type $rowType): self @@ -29,6 +39,38 @@ public function getRowType(): Type return $this->rowType; } + public static function getRowTypeForMode(Type $rowType, int $mode = self::MYSQLI_NUM): ?Type + { + if (! \in_array($mode, [self::MYSQLI_NUM, self::MYSQLI_ASSOC, self::MYSQLI_BOTH], true)) { + return null; + } + + $rowTypes = []; + foreach ($rowType->getConstantArrays() as $arrayType) { + $builder = ConstantArrayTypeBuilder::createEmpty(); + $numericIndex = 0; + + foreach ($arrayType->getKeyTypes() as $index => $keyType) { + $valueType = $arrayType->getValueTypes()[$index]; + if ($mode === self::MYSQLI_ASSOC || $mode === self::MYSQLI_BOTH) { + $builder->setOffsetValueType($keyType, $valueType); + } + + if ($mode === self::MYSQLI_NUM || $mode === self::MYSQLI_BOTH) { + $builder->setOffsetValueType(new ConstantIntegerType($numericIndex), $valueType); + $numericIndex++; + } + } + $rowTypes[] = $builder->getArray(); + } + + if (count($rowTypes) === 0) { + return null; + } + + return TypeCombinator::union(...$rowTypes); + } + public function getIterableValueType(): Type { return $this->getRowType(); diff --git a/src/Rules/MysqliFetchColumnRule.php b/src/Rules/MysqliFetchColumnRule.php new file mode 100644 index 00000000..011fbd31 --- /dev/null +++ b/src/Rules/MysqliFetchColumnRule.php @@ -0,0 +1,151 @@ + */ +final class MysqliFetchColumnRule implements Rule +{ + private ReflectionProvider $reflectionProvider; + + private bool $reportMaybes; + + public function __construct( + ReflectionProvider $reflectionProvider, + #[AutowiredParameter] + bool $reportMaybes + ) { + $this->reflectionProvider = $reflectionProvider; + $this->reportMaybes = $reportMaybes; + } + + public function getNodeType(): string + { + return CallLike::class; + } + + public function processNode(Node $node, Scope $scope): array + { + if (! $node instanceof FuncCall && ! $node instanceof MethodCall) { + return []; + } + + foreach ($node->getArgs() as $arg) { + if ($arg->unpack) { + return []; + } + } + + if ($node instanceof FuncCall) { + if (! $node->name instanceof Node\Name + || ! $this->reflectionProvider->hasFunction($node->name, $scope) + ) { + return []; + } + + $reflection = $this->reflectionProvider->getFunction($node->name, $scope); + if (strtolower($reflection->getName()) !== 'mysqli_fetch_column') { + return []; + } + + $acceptor = ParametersAcceptorSelector::selectFromArgs( + $scope, + $node->getArgs(), + $reflection->getVariants(), + $reflection->getNamedArgumentsVariants(), + ); + $call = ArgumentsNormalizer::reorderFuncArguments($acceptor, $node); + if ($call === null) { + return []; + } + + $args = $call->getArgs(); + if (! isset($args[0], $args[1])) { + return []; + } + + $resultType = $scope->getType($args[0]->value); + if (! ($resultType instanceof MysqliResultObjectType)) { + return []; + } + + $columnArg = $args[1]; + } else { // MethodCall + if (! $node->name instanceof Node\Identifier + || strtolower($node->name->toString()) !== 'fetch_column' + ) { + return []; + } + + $resultType = $scope->getType($node->var); + if (! $resultType instanceof MysqliResultObjectType) { + return []; + } + + $reflection = $scope->getMethodReflection($resultType, $node->name->toString()); + if ($reflection === null) { + return []; + } + + $acceptor = ParametersAcceptorSelector::selectFromArgs( + $scope, + $node->getArgs(), + $reflection->getVariants(), + $reflection->getNamedArgumentsVariants(), + ); + $call = ArgumentsNormalizer::reorderMethodArguments($acceptor, $node); + if ($call === null) { + return []; + } + + $args = $call->getArgs(); + if (! isset($args[0])) { + return []; + } + $columnArg = $args[0]; + } + + + $rowType = $resultType->getRowType(); + $numericRowType = MysqliResultObjectType::getRowTypeForMode($rowType); + if ($numericRowType === null) { + return []; + } + + $columnType = $scope->getType($columnArg->value); + + $hasOffset = $numericRowType->hasOffsetValueType($columnType); + if (! $this->reportMaybes && $hasOffset->maybe()) { + return []; + } + if (! $hasOffset->yes()) { + return [ + RuleErrorBuilder::message(sprintf( + 'Column offset %s %s out of range; valid offsets are %s.', + $columnType->describe(VerbosityLevel::value()), + $hasOffset->maybe() ? 'may be' : 'is', + $numericRowType->getIterableKeyType()->describe(VerbosityLevel::value()), + )) + ->identifier('dba.columnOffset') + ->line($columnArg->value->getStartLine()) + ->build(), + ]; + } + return []; + } +} diff --git a/tests/default/config/.phpunit-phpstan-dba-mysqli.cache b/tests/default/config/.phpunit-phpstan-dba-mysqli.cache index 3026c3fb..f561321c 100644 --- a/tests/default/config/.phpunit-phpstan-dba-mysqli.cache +++ b/tests/default/config/.phpunit-phpstan-dba-mysqli.cache @@ -77,9 +77,6 @@ FROM ada' => ), 'SELECT adaid FROM ada LIMIT 1 FOR SHARE' => array ( - 'error' => - \staabm\PHPStanDba\Valid::__set_state(array( - )), 'result' => array ( 5 => @@ -130,9 +127,6 @@ FROM ada' => ), 'SELECT adaid FROM ada LIMIT 1 OFFSET 1' => array ( - 'error' => - \staabm\PHPStanDba\Valid::__set_state(array( - )), 'result' => array ( 5 => @@ -143,9 +137,6 @@ FROM ada' => ), 'SELECT adaid FROM ada LIMIT 1 OFFSET 1 FOR UPDATE' => array ( - 'error' => - \staabm\PHPStanDba\Valid::__set_state(array( - )), 'result' => array ( 5 => @@ -236,9 +227,6 @@ FROM ada' => ), 'SELECT akid FROM ak WHERE eadavk>1.0' => array ( - 'error' => - \staabm\PHPStanDba\Valid::__set_state(array( - )), 'result' => array ( 5 => @@ -559,9 +547,6 @@ FROM ada' => ), 'SELECT email, adaid FROM ada WHERE gesperrt = \'1\'' => array ( - 'error' => - \staabm\PHPStanDba\Valid::__set_state(array( - )), 'result' => array ( 5 => diff --git a/tests/rules/MysqliFetchColumnRuleTest.php b/tests/rules/MysqliFetchColumnRuleTest.php new file mode 100644 index 00000000..f4f488dc --- /dev/null +++ b/tests/rules/MysqliFetchColumnRuleTest.php @@ -0,0 +1,104 @@ + + */ +class MysqliFetchColumnRuleTest extends RuleTestCase +{ + private bool $reportMaybes = false; + + protected function setUp(): void + { + parent::setUp(); + + QueryReflection::getRuntimeConfiguration()->debugMode(true); + } + + protected function tearDown(): void + { + QueryReflection::getRuntimeConfiguration()->debugMode(false); + } + + protected function getRule(): Rule + { + return new MysqliFetchColumnRule( + self::getContainer()->getByType(ReflectionProvider::class), + $this->reportMaybes + ); + } + + public static function getAdditionalConfigFiles(): array + { + return [ + __DIR__ . '/../../config/dba.neon', + ]; + } + + public function testFetchColumnRule(): void + { + if ('mysqli' !== getenv('DBA_REFLECTOR')) { + self::markTestSkipped('Test requires mysqli'); + } + if (PHP_VERSION_ID < 80100) { + self::markTestSkipped('Test requires PHP 8.1'); + } + $this->reportMaybes = true; + $this->analyse([__DIR__ . '/data/mysqli-fetch-column.php'], [ + [ + 'Column offset 999 is out of range; valid offsets are 0|1|2.', + 21, + ], + [ + 'Column offset 0|999 may be out of range; valid offsets are 0|1|2.', + 24, + ], + [ + 'Column offset int<0, 8> may be out of range; valid offsets are 0|1|2.', + 28, + ], + [ + 'Column offset 999 is out of range; valid offsets are 0|1|2.', + 43, + ], + [ + 'Column offset 0|999 may be out of range; valid offsets are 0|1|2.', + 46, + ], + [ + 'Column offset int<0, 8> may be out of range; valid offsets are 0|1|2.', + 50, + ], + ]); + } + + public function testFetchColumnRuleNoMaybes(): void + { + if ('mysqli' !== getenv('DBA_REFLECTOR')) { + self::markTestSkipped('Test requires mysqli'); + } + if (PHP_VERSION_ID < 80100) { + self::markTestSkipped('Test requires PHP 8.1'); + } + $this->reportMaybes = false; + $this->analyse([__DIR__ . '/data/mysqli-fetch-column.php'], [ + [ + 'Column offset 999 is out of range; valid offsets are 0|1|2.', + 21, + ], + [ + 'Column offset 999 is out of range; valid offsets are 0|1|2.', + 43, + ], + ]); + } +} diff --git a/tests/rules/config/.phpunit-phpstan-dba-mysqli.cache b/tests/rules/config/.phpunit-phpstan-dba-mysqli.cache index 8059ff4d..279ebd53 100644 --- a/tests/rules/config/.phpunit-phpstan-dba-mysqli.cache +++ b/tests/rules/config/.phpunit-phpstan-dba-mysqli.cache @@ -349,6 +349,16 @@ Simulated query: SELECT FROM WHERE LIMIT 0', ), ), ), + 'SELECT c_varchar255, c_smallint, c_float FROM typemix' => + array ( + 'result' => + array ( + 3 => + array ( + 'type-description' => 'array{c_varchar255: string, c_smallint: int<-32768, 32767>, c_float: float}', + ), + ), + ), 'SELECT doesNotExist, adaid, gesperrt, freigabe1u1 FROM ada' => array ( 'error' => diff --git a/tests/rules/data/mysqli-fetch-column.php b/tests/rules/data/mysqli-fetch-column.php new file mode 100644 index 00000000..c22c1790 --- /dev/null +++ b/tests/rules/data/mysqli-fetch-column.php @@ -0,0 +1,54 @@ +fetch_column(); + + // valid column + $col1 = $result->fetch_column(1); + + // out-of-range column + $col999 = $result->fetch_column(999); + + // multiple possible columns (one invalid) + $col0_or_999 = $result->fetch_column(rand() ? 0 : 999); + + // range of possible columns (some invalid) + for($i=0; $i<9; $i++) { + $col0_to_9 = $result->fetch_column($i); + } + } + + public function proceduralFetchColumn(mysqli $mysqli) + { + $result = mysqli_query($mysqli, 'SELECT c_varchar255, c_smallint, c_float FROM typemix'); + + // default column + $col0 = mysqli_fetch_column($result); + + // valid column + $col1 = mysqli_fetch_column($result, 1); + + // out-of-range column + $col999 = mysqli_fetch_column($result, 999); + + // multiple possible columns (one invalid) + $col0_or_999 = mysqli_fetch_column($result, rand() ? 0 : 999); + + // range of possible columns (some invalid) + for($i=0; $i<9; $i++) { + $col0_to_9 = mysqli_fetch_column($result, $i); + assertType('float|int<-32768, 32767>|string|false', $col0_to_2); + } + } +}