From a25574bd579f14a9d66af6b878ddff0e6012bc6f Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Wed, 25 Nov 2026 14:48:12 -0800 Subject: [PATCH 01/21] Code Quality: Type wpdb query results from the columns selected. Add a PHPStan extension that types the results of `wpdb::get_var()`, `get_row()`, `get_col()` and `get_results()` from the columns their query selects, so that they no longer need an inline `@var` tag. `WpdbQueryVisitor` reconstructs the query text from the syntax tree, following the variables it is built up in. `WpdbSchema` reads the column types of the core tables from the `CREATE TABLE` statements in `wp_get_db_schema()`. `WpdbSelectParser` reads the select list and the tables in the `FROM` clause. The extension then refines the declared return type: each `stdClass` row becomes an object shape, each row array an array shape, and `OBJECT_K` results are keyed by the first column. The sharper types expose more cases of numeric strings from query results being passed to `int` parameters, so the `argument.type` baseline is regenerated. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- tests/phpstan/README.md | 20 + ...bQueryDynamicMethodReturnTypeExtension.php | 406 +++++++++++++ tests/phpstan/WpdbQueryVisitor.php | 348 ++++++++++++ tests/phpstan/WpdbSchema.php | 174 ++++++ tests/phpstan/WpdbSelectParser.php | 537 ++++++++++++++++++ tests/phpstan/base.neon | 18 + tests/phpstan/baselines/argument.type.neon | 120 +++- 7 files changed, 1603 insertions(+), 20 deletions(-) create mode 100644 tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php create mode 100644 tests/phpstan/WpdbQueryVisitor.php create mode 100644 tests/phpstan/WpdbSchema.php create mode 100644 tests/phpstan/WpdbSelectParser.php diff --git a/tests/phpstan/README.md b/tests/phpstan/README.md index 520f8c76ebdb5..541393c0f55f7 100644 --- a/tests/phpstan/README.md +++ b/tests/phpstan/README.md @@ -209,6 +209,26 @@ These identifiers are specific to WordPress, and can be ignored or baselined lik | `wordpress.hookDocReferenceHookMissing` | The referenced file exists, but documents no hook of that name. Either the reference is stale, or the canonical docblock has moved. | | `wordpress.hookParamCountMismatch` | The call passes a different number of arguments than the docblock documents `@param` tags for. Passing fewer risks an `ArgumentCountError` in a callback registered for the documented count; passing more silently drops the extra argument and leaves the documentation misleading. | +### Database query results + +`WpdbQueryDynamicMethodReturnTypeExtension` types the results of `$wpdb->get_var()`, `get_row()`, `get_col()` and `get_results()` from the columns their query selects, so that they need no inline `@var` tag. For example: + +```php +$post = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_title FROM $wpdb->posts WHERE ID = %d", $id ) ); +``` + +is typed `(object{ID: decimal-int-string, post_title: string}&stdClass)|null` rather than `stdClass|null`. Likewise, `ARRAY_A` and `ARRAY_N` rows become array shapes, `OBJECT_K` results are keyed by the first column's type, and `get_var()` and `get_col()` give the type of the column they return. + +- **The columns of core tables are typed from the schema.** They are read from the `CREATE TABLE` statements in `wp_get_db_schema()`, so a column added there needs no change here. `wpdb` returns every value as a string, or null for SQL `NULL`, so an integer column is a `decimal-int-string`, a `DATETIME` column a `non-falsy-string`, and a column without `NOT NULL` is nullable. The `spam` and `deleted` columns, which `users` only has on multisite, are optional. +- **Select expressions are named and typed as MySQL does.** An alias names a column, as does the text of an expression without one, like `COUNT(*)`. `COUNT()` is a `decimal-int-string`, `SUM()` and `AVG()` are a nullable `numeric-string`, `MIN()` and `MAX()` of a column are the column's type or null, and a literal is that constant string. Anything else, including a column of a table that is not a core table, is `string|null`, which is what any value can be. +- **A query built up in variables is followed.** The query is reconstructed from the syntax tree, by `WpdbQueryVisitor`: literals, interpolation, `$wpdb->prepare()` and concatenation are joined, `$wpdb->posts` and the like name the table, and a variable is replaced by what the statements before the call assign and append to it. Only what the select list and the `FROM` clause need must be known, so a `WHERE` clause built from parameters does no harm. The variable is not followed through a loop which writes to it, or through a branch which does more than append to it. + +Where the columns cannot be determined, such as for `SELECT *` from a table that is not a core table, for a select list holding a variable, or for a query that is not `SELECT`, the method's declared return type is used as before. The cases in which a method returns null or an empty array are as declared either way, since they depend on its arguments rather than the query. + +These types assume `wpdb` itself. A `db.php` drop-in that replaces it could return values of other types. + +Since the schema is read from `schema.php` rather than through PHPStan's reflection, PHPStan does not know that the files with queries depend on it. After changing a column in `schema.php`, [clear the cache](#clear-the-cache-after-changing-anything-in-this-directory) so that the queries are analyzed again. + ## Ignoring and baselining errors As we adopt PHPStan iteratively, you may be faced with false positives due to legacy code, or code that is not worth changing at this time. diff --git a/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php new file mode 100644 index 0000000000000..ffdc6b1241232 --- /dev/null +++ b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php @@ -0,0 +1,406 @@ +get_row( $wpdb->prepare( "SELECT ID, post_title FROM $wpdb->posts WHERE ID = %d", $id ) ); + * + * PHPStan will infer `(object{ ID: decimal-int-string, post_title: string }&stdClass)|null` + * rather than `stdClass|null`, with no need for an inline `@var` tag. + * + * The query's text comes from `WpdbQueryVisitor`, or from the query's type + * when that is a constant string. `WpdbSelectParser` reads the columns from it, + * typed from the core schema by `WpdbSchema`. + * + * The method's declared return type is kept, and refined: each `stdClass` row + * in it becomes an object shape, each row array an array shape, and each + * value the column's type. So the cases in which a method returns null or an + * empty array, which depend on its arguments rather than the query, are as + * declared. Where the columns are not known well enough to refine a type, it + * is left as declared. + * + * This assumes `wpdb` itself, with mysqli, which returns every value as a + * string or null. A drop-in replacing it could return other types. + */ +class WpdbQueryDynamicMethodReturnTypeExtension implements DynamicMethodReturnTypeExtension { + + /** + * Resolver for the column types, which are PHPDoc type strings. + * + * @var TypeStringResolver + */ + private TypeStringResolver $type_string_resolver; + + /** + * Parser for the select list of a query. + * + * @var WpdbSelectParser + */ + private WpdbSelectParser $parser; + + /** + * Resolved column types, keyed by PHPDoc type string. + * + * @var array + */ + private array $types = array(); + + /** + * Constructor. + * + * @param TypeStringResolver $type_string_resolver Resolver for PHPDoc type strings. + */ + public function __construct( TypeStringResolver $type_string_resolver ) { + $this->type_string_resolver = $type_string_resolver; + $this->parser = new WpdbSelectParser( new WpdbSchema() ); + } + + /** + * Gets the class whose methods this extension types. + * + * @return string + */ + public function getClass(): string { + return 'wpdb'; + } + + /** + * Determines whether this extension types the given method. + * + * @param MethodReflection $methodReflection Method being analyzed. + * @return bool + */ + public function isMethodSupported( MethodReflection $methodReflection ): bool { + return in_array( strtolower( $methodReflection->getName() ), WpdbQueryVisitor::METHODS, true ); + } + + /** + * Types the result of a query method call from its query's columns. + * + * @link https://developer.wordpress.org/reference/classes/wpdb/get_var/ + * @link https://developer.wordpress.org/reference/classes/wpdb/get_row/ + * @link https://developer.wordpress.org/reference/classes/wpdb/get_col/ + * @link https://developer.wordpress.org/reference/classes/wpdb/get_results/ + * + * @param MethodReflection $methodReflection Method being analyzed. + * @param MethodCall $methodCall The method call node. + * @param Scope $scope Analysis scope. + * @return Type|null Type, or null to use the declared return type. + */ + public function getTypeFromMethodCall( MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope ): ?Type { + $args = $methodCall->getArgs(); + if ( ! isset( $args[0] ) ) { + return null; + } + + $query = null; + $constants = $scope->getType( $args[0]->value )->getConstantStrings(); + if ( 1 === count( $constants ) ) { + $query = $constants[0]->getValue(); + } else { + $attribute = $methodCall->getAttribute( WpdbQueryVisitor::ATTRIBUTE ); + if ( is_string( $attribute ) ) { + $query = $attribute; + } + } + if ( null === $query ) { + return null; + } + + $result = $this->parser->parse( $query ); + if ( null === $result || array() === $result['columns'] ) { + return null; + } + + $columns = array(); + foreach ( $result['columns'] as $column ) { + $columns[] = array( + 'name' => $column['name'], + 'type' => $this->resolve_type( $column['type'] ), + 'optional' => $column['optional'], + ); + } + + switch ( strtolower( $methodReflection->getName() ) ) { + case 'get_var': + $value = $this->get_positional_value_type( $columns, $result['complete'], $args[1]->value ?? null, $scope ); + return null !== $value ? TypeCombinator::addNull( $value ) : null; + + case 'get_col': + $value = $this->get_positional_value_type( $columns, $result['complete'], $args[1]->value ?? null, $scope ); + return null !== $value ? TypeCombinator::intersect( new ArrayType( new IntegerType(), $value ), new AccessoryArrayListType() ) : null; + + default: + $declared = ParametersAcceptorSelector::selectFromArgs( $scope, $args, $methodReflection->getVariants() )->getReturnType(); + $refined = $this->refine_rows( $declared, $columns, $result['complete'] ); return $refined->equals( $declared ) ? null : $refined; + } + } + + /** + * Gets the type `get_var()` or `get_col()` returns for the value in a row. + * + * Both return null for an empty string as well as for SQL NULL, since `get_col()` uses `get_var()`. + * + * @param list $columns Columns. + * @param bool $complete Whether the columns are all known. + * @param \PhpParser\Node\Expr|null $x The column index argument, if any. + * @param Scope $scope Analysis scope. + * @return Type|null Type, or null if unknown. + */ + private function get_positional_value_type( array $columns, bool $complete, ?\PhpParser\Node\Expr $x, Scope $scope ): ?Type { + $positional = $this->get_positional_columns( $columns, $complete ); + + $indexes = array( 0 ); + if ( null !== $x ) { + $indexes = array(); + foreach ( $scope->getType( $x )->getConstantScalarValues() as $value ) { + if ( ! is_int( $value ) ) { + return null; + } + $indexes[] = $value; + } + if ( array() === $indexes ) { + // Any column. + if ( count( $positional ) !== count( $columns ) || ! $complete ) { + return null; + } + $indexes = array_keys( $columns ); + } + } + + $types = array(); + foreach ( $indexes as $index ) { + if ( ! isset( $positional[ $index ] ) ) { + // Past the known columns, or an index with no column, for which the value is null. + if ( $complete && count( $positional ) === count( $columns ) ) { + $types[] = new NullType(); + continue; + } + return null; + } + $type = $positional[ $index ]['type']; + $non_null = TypeCombinator::removeNull( $type ); + $types[] = TypeCombinator::intersect( $non_null, new StringType(), new AccessoryNonEmptyStringType() ); + if ( ! $type->isNull()->no() || ! $non_null->isSuperTypeOf( new ConstantStringType( '' ) )->no() ) { + $types[] = new NullType(); + } + } + + return TypeCombinator::union( ...$types ); + } + + /** + * Gets the columns whose positions are known. + * + * A column only present on some sites shifts the positions of those after it, and the columns after an unknown + * one are unknown. + * + * @param list $columns Columns. + * @param bool $complete Whether the columns are all known. + * @return list Columns, from the first. + */ + private function get_positional_columns( array $columns, bool $complete ): array { + $positional = array(); + foreach ( $columns as $index => $column ) { + if ( $column['optional'] ) { + // Its own position is known, but whether it is there is not. + $is_last = ( count( $columns ) - 1 === $index ) && $complete; + if ( ! $is_last ) { + break; + } + } + $positional[] = $column; + } + return $positional; + } + + /** + * Refines the rows in a declared return type of `get_row()` or `get_results()`. + * + * @param Type $declared Declared return type. + * @param list $columns Columns. + * @param bool $complete Whether the columns are all known. + * @return Type + */ + private function refine_rows( Type $declared, array $columns, bool $complete ): Type { + $properties = $complete ? $this->get_properties( $columns ) : null; + + $object_row = null; + $assoc_row = null; + if ( null !== $properties ) { + $shape = array(); + $optional = array(); + $builder = ConstantArrayTypeBuilder::createEmpty(); + foreach ( $properties as $name => $property ) { + // A numeric name, like that of `SELECT 1`, is an integer key. + $name = (string) $name; + $shape[ $name ] = $property['type']; + if ( $property['optional'] ) { + $optional[] = $name; + } + $builder->setOffsetValueType( ( new ConstantStringType( $name ) )->toArrayKey(), $property['type'], $property['optional'] ); + } + $object_row = TypeCombinator::intersect( new ObjectShapeType( $shape, $optional ), new ObjectType( 'stdClass' ) ); + $assoc_row = $builder->getArray(); + } + + $list_row = null; + if ( $complete ) { + $builder = ConstantArrayTypeBuilder::createEmpty(); + foreach ( $columns as $index => $column ) { + $builder->setOffsetValueType( new ConstantIntegerType( $index ), $column['type'], $column['optional'] ); + } + $list_row = $builder->getArray(); + } + + // `OBJECT_K` keys the rows by the first column's value, with null as ''. + $key = null; + if ( isset( $columns[0] ) && ! $columns[0]['optional'] ) { + $key = $columns[0]['type']; + if ( ! $key->isNull()->no() ) { + $key = TypeCombinator::union( TypeCombinator::removeNull( $key ), new ConstantStringType( '' ) ); + } + $key = $key->toArrayKey(); + } + + return self::replace_rows( + $declared, + array( + 'object' => $object_row, + 'assoc' => $assoc_row, + 'list' => $list_row, + 'key' => $key, + ) + ); + } + + /** + * Replaces the rows in a declared return type of `get_row()` or `get_results()`. + * + * An array is rebuilt rather than traversed, since traversing a `list` would reach its `list` accessory + * apart from its value type, and the accessory alone also reads as an array of mixed. + * + * @param Type $type Type. + * @param array{ object: Type|null, assoc: Type|null, list: Type|null, key: Type|null } $rows { + * Types to replace with, each null to leave as is. + * + * @type Type|null $object Row object, replacing `stdClass`. + * @type Type|null $assoc Associative row array, replacing an `array`. + * @type Type|null $list List row array, replacing a `list`. + * @type Type|null $key Key of the rows keyed by `OBJECT_K`, replacing the key of an `array`. + * } + * @return Type + */ + private static function replace_rows( Type $type, array $rows ): Type { + return TypeTraverser::map( + $type, + static function ( Type $type, callable $traverse ) use ( $rows ): Type { + if ( $type instanceof ObjectType && 'stdClass' === $type->getClassName() ) { + return $rows['object'] ?? $type; + } + + if ( ! $type->isArray()->yes() ) { + return $traverse( $type ); + } + + $key = $type->getIterableKeyType(); + $value = $type->getIterableValueType(); + $is_list = $type->isList()->yes(); + + // A row array. + if ( $value instanceof MixedType ) { + return ( $is_list ? $rows['list'] : $rows['assoc'] ) ?? $type; + } + + // Rows keyed by `OBJECT_K`, which unlike the other results may have string keys. + if ( $value instanceof ObjectType && 'stdClass' === $value->getClassName() && ! $key->isString()->no() ) { + $key = $rows['key'] ?? $key; + } + + $array = new ArrayType( $key, self::replace_rows( $value, $rows ) ); + return $is_list ? TypeCombinator::intersect( $array, new AccessoryArrayListType() ) : $array; + } + ); + } + + /** + * Gets the properties of a row object, which are the columns by name. + * + * A later column replaces an earlier one with the same name, as in the row object. + * + * @param list $columns Columns. + * @return array|null Properties, or null if a column's name is unknown. + */ + private function get_properties( array $columns ): ?array { + $properties = array(); + foreach ( $columns as $column ) { + if ( null === $column['name'] ) { + return null; + } + + $earlier = $properties[ $column['name'] ] ?? null; + if ( null !== $earlier && $column['optional'] ) { + // It only replaces the earlier one when present. + $properties[ $column['name'] ] = array( + 'type' => TypeCombinator::union( $earlier['type'], $column['type'] ), + 'optional' => $earlier['optional'], + ); + continue; + } + + $properties[ $column['name'] ] = array( + 'type' => $column['type'], + 'optional' => $column['optional'], + ); + } + return $properties; + } + + /** + * Resolves a PHPDoc type string, once. + * + * @param string $type_string PHPDoc type. + * @return Type + */ + private function resolve_type( string $type_string ): Type { + if ( ! isset( $this->types[ $type_string ] ) ) { + $this->types[ $type_string ] = $this->type_string_resolver->resolve( $type_string ); + } + return $this->types[ $type_string ]; + } +} diff --git a/tests/phpstan/WpdbQueryVisitor.php b/tests/phpstan/WpdbQueryVisitor.php new file mode 100644 index 0000000000000..f20f6b773b49f --- /dev/null +++ b/tests/phpstan/WpdbQueryVisitor.php @@ -0,0 +1,348 @@ +posts`, so the query text cannot be + * read from its type. And a query is often built up in a variable before the + * call, which a type extension cannot see the statements of. So this visitor + * reconstructs the text from the syntax tree instead, before analysis: + * + * - String literals, interpolation and concatenation are joined. + * - A table property on `$wpdb`, like `$wpdb->posts`, becomes the placeholder + * `{wpdb:posts}`, so that the query parser knows which table it names. + * - `$wpdb->prepare( $query, ... )` is replaced by its query. + * - A variable is replaced by the value assigned to it by the nearest preceding + * `$var = ...;` statement, followed by any `$var .= ...;` statements after it. + * The search walks back through the preceding statements, out through the + * enclosing blocks, and stops at the enclosing function. + * - Anything else is replaced by the placeholder `{?}`, for a part whose text + * is unknown. + * + * The search for a variable's value gives up, making the whole value unknown, + * when the variable is written in a way that may not be straight-line: by a + * statement nested in a preceding block, or by an enclosing loop or other block + * (other than an `if`) which the call is in. A nested statement which only + * appends to the variable is the exception: since text it appends can only + * follow what came before, it is taken as an unknown suffix, and the start of + * the query, which holds its select list, stays known. + * + * The text is only used to read the select list and the tables in the query, + * so an unknown part elsewhere, like in the `WHERE` clause, does no harm. + * + * Registered as `phpstan.parser.richParserNodeVisitor` in `base.neon`. + */ +final class WpdbQueryVisitor extends NodeVisitorAbstract { + + /** + * Name of the attribute holding the reconstructed query on a method call node. + */ + public const ATTRIBUTE = 'wordpressWpdbQuery'; + + /** + * Placeholder for a part of the query whose text is unknown. + */ + public const UNKNOWN = '{?}'; + + /** + * Methods of `wpdb` whose first parameter is a query to reconstruct. + */ + public const METHODS = array( 'get_var', 'get_row', 'get_col', 'get_results' ); + + /** + * Maximum number of variables followed in reconstructing one query. + */ + private const MAX_DEPTH = 10; + + /** + * Finder for writes to variables. + * + * @var NodeFinder + */ + private NodeFinder $node_finder; + + /** + * Constructor. + */ + public function __construct() { + $this->node_finder = new NodeFinder(); + } + + /** + * Annotates the query method calls in the file before it is traversed. + * + * The whole file is walked here rather than node by node, since resolving a + * variable needs the statements preceding the call, which a visitor's + * `enterNode()` does not have. + * + * @param array $nodes Top-level nodes about to be traversed. + * @return array|null Null, since the nodes are not replaced. + */ + public function beforeTraverse( array $nodes ): ?array { + $this->walk_statements( array_values( $nodes ), array() ); + return null; + } + + /** + * Walks a list of statements. + * + * @param list $stmts Statements. + * @param list, 1: int }> $frames Positions of the statements enclosing the list, outermost + * first. Each is a statement list and the index in it. + */ + private function walk_statements( array $stmts, array $frames ): void { + foreach ( $stmts as $index => $stmt ) { + $position = $frames; + $position[] = array( $stmts, $index ); + $this->walk_node( $stmt, $position ); + } + } + + /** + * Walks a node, annotating the query method calls in it. + * + * @param Node $node Node. + * @param list, 1: int }> $position Position of the statement the node is in. + */ + private function walk_node( Node $node, array $position ): void { + foreach ( $node->getSubNodeNames() as $name ) { + $sub_node = $node->$name; + if ( is_array( $sub_node ) ) { + if ( 'stmts' === $name ) { + // A function's body starts a new scope, so the variables outside it are not followed. + $stmts = array_values( array_filter( $sub_node, static fn ( $stmt ): bool => $stmt instanceof Node ) ); + $this->walk_statements( $stmts, $node instanceof FunctionLike ? array() : $position ); + } else { + foreach ( $sub_node as $item ) { + if ( $item instanceof Node ) { + $this->walk_node( $item, $position ); + } + } + } + } elseif ( $sub_node instanceof Node ) { + $this->walk_node( $sub_node, $position ); + } + } + + if ( + $node instanceof MethodCall + && $node->name instanceof Identifier + && in_array( $node->name->toLowerString(), self::METHODS, true ) + && isset( $node->args[0] ) + && $node->args[0] instanceof Arg + ) { + $query = $this->evaluate( $node->args[0]->value, $position, 0 ); + if ( self::UNKNOWN !== $query ) { + $node->setAttribute( self::ATTRIBUTE, $query ); + } + } + } + + /** + * Reconstructs the text of a string expression. + * + * @param Expr $expr Expression. + * @param list, 1: int }> $position Position of the statement the expression is in. + * @param int $depth Number of variables followed so far. + * @return string Text, with `{wpdb:}` for a table and `{?}` for each unknown part. + */ + private function evaluate( Expr $expr, array $position, int $depth ): string { + if ( $expr instanceof String_ ) { + return $expr->value; + } + + if ( $expr instanceof InterpolatedString ) { + $text = ''; + foreach ( $expr->parts as $part ) { + $text .= $part instanceof InterpolatedStringPart ? $part->value : $this->evaluate( $part, $position, $depth ); + } + return $text; + } + + if ( $expr instanceof Concat ) { + return $this->evaluate( $expr->left, $position, $depth ) . $this->evaluate( $expr->right, $position, $depth ); + } + + if ( $expr instanceof PropertyFetch && $this->is_wpdb( $expr->var ) && $expr->name instanceof Identifier ) { + return '{wpdb:' . $expr->name->toString() . '}'; + } + + if ( + $expr instanceof MethodCall + && $this->is_wpdb( $expr->var ) + && $expr->name instanceof Identifier + && 'prepare' === $expr->name->toLowerString() + && isset( $expr->args[0] ) + && $expr->args[0] instanceof Arg + ) { + return $this->evaluate( $expr->args[0]->value, $position, $depth ); + } + + if ( $expr instanceof Variable && is_string( $expr->name ) && $depth < self::MAX_DEPTH ) { + return $this->resolve_variable( $expr->name, $position, $depth + 1 ); + } + + return self::UNKNOWN; + } + + /** + * Reconstructs the value of a variable at a position from the statements preceding it. + * + * @param string $name Variable name. + * @param list, 1: int }> $position Position of the statement reading the variable. + * @param int $depth Number of variables followed so far, including this one. + * @return string Text, with `{wpdb:
}` for a table and `{?}` for each unknown part. + */ + private function resolve_variable( string $name, array $position, int $depth ): string { + // Text appended to the variable between its assignment and the position. + $appended = ''; + + for ( $level = count( $position ) - 1; $level >= 0; $level-- ) { + list( $stmts, $index ) = $position[ $level ]; + + /* + * The statement at an outer level is the block the position is in. A write to the variable anywhere in a + * loop may have run before the position, in an earlier iteration, and likewise in the try block for a + * position in a catch block, and so on. The exception is an `if`: of its branches, only the one the + * position is in has run. + */ + if ( count( $position ) - 1 !== $level && ! $stmts[ $index ] instanceof Stmt\If_ && $this->writes_variable( $stmts[ $index ], $name, false ) ) { + return self::UNKNOWN; + } + + for ( $i = $index - 1; $i >= 0; $i-- ) { + $stmt = $stmts[ $i ]; + + $stmt_position = array_slice( $position, 0, $level ); + $stmt_position[] = array( $stmts, $i ); + + if ( $stmt instanceof Stmt\Expression && $this->is_variable( $stmt->expr instanceof Assign ? $stmt->expr->var : null, $name ) ) { + /** @var Assign $assign */ + $assign = $stmt->expr; + return $this->evaluate( $assign->expr, $stmt_position, $depth ) . $appended; + } + + if ( $stmt instanceof Stmt\Expression && $stmt->expr instanceof AssignOp\Concat && $this->is_variable( $stmt->expr->var, $name ) ) { + $appended = $this->evaluate( $stmt->expr->expr, $stmt_position, $depth ) . $appended; + continue; + } + + if ( $this->writes_variable( $stmt, $name, true ) ) { + // Something other than an append, which may replace the value. + return self::UNKNOWN; + } + + if ( $this->writes_variable( $stmt, $name, false ) ) { + // A nested append, which may or may not have run. + $appended = self::UNKNOWN . $appended; + } + } + } + + // The variable is not assigned in the function, so it is a parameter, global or the like. + return self::UNKNOWN; + } + + /** + * Determines whether a node may write to a variable. + * + * Writes through a reference, like a by-reference argument, are not detected. + * + * @param Node $node Node to search. + * @param string $name Variable name. + * @param bool $ignore_appends Whether to ignore writes with `.=`. + * @return bool + */ + private function writes_variable( Node $node, string $name, bool $ignore_appends ): bool { + $found = $this->node_finder->findFirst( + $node, + function ( Node $node ) use ( $name, $ignore_appends ): bool { + if ( $node instanceof Assign || $node instanceof AssignRef ) { + return $this->contains_variable( $node->var, $name ); + } + if ( $node instanceof AssignOp ) { + return ! ( $ignore_appends && $node instanceof AssignOp\Concat ) && $this->contains_variable( $node->var, $name ); + } + if ( $node instanceof Stmt\Foreach_ ) { + return $this->contains_variable( $node->valueVar, $name ) || ( null !== $node->keyVar && $this->contains_variable( $node->keyVar, $name ) ); + } + if ( $node instanceof Stmt\Global_ || $node instanceof Stmt\Unset_ ) { + return $this->contains_variable( $node, $name ); + } + if ( $node instanceof Node\StaticVar ) { + return $this->is_variable( $node->var, $name ); + } + return false; + } + ); + return null !== $found; + } + + /** + * Determines whether a node is or contains a variable, like a `list()` being assigned to. + * + * @param Node $node Node. + * @param string $name Variable name. + * @return bool + */ + private function contains_variable( Node $node, string $name ): bool { + return null !== $this->node_finder->findFirst( + $node, + function ( Node $node ) use ( $name ): bool { + return $this->is_variable( $node, $name ); + } + ); + } + + /** + * Determines whether a node is a variable. + * + * @param Node|null $node Node. + * @param string $name Variable name. + * @return bool + */ + private function is_variable( ?Node $node, string $name ): bool { + return $node instanceof Variable && $node->name === $name; + } + + /** + * Determines whether an expression is the `$wpdb` global. + * + * @param Expr $expr Expression. + * @return bool + */ + private function is_wpdb( Expr $expr ): bool { + return $this->is_variable( $expr, 'wpdb' ); + } +} diff --git a/tests/phpstan/WpdbSchema.php b/tests/phpstan/WpdbSchema.php new file mode 100644 index 0000000000000..48216b056971f --- /dev/null +++ b/tests/phpstan/WpdbSchema.php @@ -0,0 +1,174 @@ +>|null + * @phpstan-var array>|null + */ + private ?array $tables = null; + + /** + * Path to `schema.php`. + * + * @var string + */ + private string $schema_file; + + /** + * Constructor. + * + * @param string|null $schema_file Optional. Path to `schema.php`. Defaults to the one in `src/`. + */ + public function __construct( ?string $schema_file = null ) { + $this->schema_file = $schema_file ?? dirname( __DIR__, 2 ) . '/src/wp-admin/includes/schema.php'; + } + + /** + * Determines whether a table is a core table. + * + * @param string $table Table, by its `wpdb` property name, like `posts`. + * @return bool + */ + public function has_table( string $table ): bool { + return isset( $this->get_tables()[ $table ] ); + } + + /** + * Gets the columns of a table, in order. + * + * @param string $table Table, by its `wpdb` property name, like `posts`. + * @return list + * @phpstan-return list + */ + public function get_columns( string $table ): array { + return array_values( $this->get_tables()[ $table ] ?? array() ); + } + + /** + * Gets a column of a table. + * + * @param string $table Table, by its `wpdb` property name, like `posts`. + * @param string $column Column name, in any case, since MySQL column names are case-insensitive. + * @return array{ name: non-empty-string, type: non-empty-string, optional: bool }|null Column, or null if the table + * has no such column. + * @phpstan-return Column|null + */ + public function get_column( string $table, string $column ): ?array { + return $this->get_tables()[ $table ][ strtolower( $column ) ] ?? null; + } + + /** + * Reads the tables from `schema.php`, once. + * + * @return array> + * @phpstan-return array> + */ + private function get_tables(): array { + if ( null !== $this->tables ) { + return $this->tables; + } + + $this->tables = array(); + + $source = file_get_contents( $this->schema_file ); + if ( false === $source ) { + return $this->tables; + } + + preg_match_all( '/CREATE TABLE \$wpdb->(\w+) \((.*?)\n\) \$charset_collate;/s', $source, $matches, PREG_SET_ORDER ); + foreach ( $matches as $match ) { + $table = $match[1]; + $is_redefine = isset( $this->tables[ $table ] ); + + foreach ( explode( "\n", $match[2] ) as $line ) { + if ( ! preg_match( '/^\s*(\w+)\s+(\w+)(.*)$/', $line, $column_match ) ) { + continue; + } + list( , $name, $sql_type, $definition ) = $column_match; + if ( in_array( strtoupper( $name ), array( 'PRIMARY', 'KEY', 'UNIQUE', 'INDEX', 'FULLTEXT', 'SPATIAL', 'CONSTRAINT', 'FOREIGN' ), true ) ) { + continue; + } + + $key = strtolower( $name ); + if ( $is_redefine && isset( $this->tables[ $table ][ $key ] ) ) { + continue; + } + + $type = self::get_value_type( $sql_type ); + if ( ! preg_match( '/\bNOT NULL\b/i', $definition ) ) { + $type .= '|null'; + } + + $this->tables[ $table ][ $key ] = array( + 'name' => $name, + 'type' => $type, + 'optional' => $is_redefine, + ); + } + } + + return $this->tables; + } + + /** + * Gets the type of the non-null values `wpdb` returns for a column type. + * + * @param string $sql_type SQL column type, like `bigint` or `varchar`. + * @return non-empty-string PHPDoc type. + */ + public static function get_value_type( string $sql_type ): string { + switch ( strtolower( $sql_type ) ) { + case 'tinyint': + case 'smallint': + case 'mediumint': + case 'int': + case 'integer': + case 'bigint': + return 'decimal-int-string'; + case 'decimal': + case 'numeric': + case 'float': + case 'double': + case 'real': + return 'numeric-string'; + case 'datetime': + case 'date': + case 'timestamp': + case 'time': + // Even the zero value, like '0000-00-00 00:00:00', is not falsy. + return 'non-falsy-string'; + default: + return 'string'; + } + } +} diff --git a/tests/phpstan/WpdbSelectParser.php b/tests/phpstan/WpdbSelectParser.php new file mode 100644 index 0000000000000..1257f3fe48427 --- /dev/null +++ b/tests/phpstan/WpdbSelectParser.php @@ -0,0 +1,537 @@ +}` and an unknown part is `{?}`. + * + * Each column is typed as follows: + * + * - A column of a core table, including each one a `*` or `alias.*` expands + * to, has the type `WpdbSchema` gives it. + * - `COUNT()` is a `decimal-int-string`, `SUM()` and `AVG()` are a + * `numeric-string` or null, and `MIN()` and `MAX()` of a core column are the + * column's type or null. + * - A number or string literal is that constant string. + * - Anything else is `string|null`, which is every value `wpdb` can return. + * + * A column's name is its alias, or else its name for a column reference, or + * else the text of its expression, as MySQL names them. + * + * The columns are incomplete from the first one whose count is not known: a + * `*` over a table that is not a core table, or a select expression with an + * unknown part outside any parentheses, since that part could hold several + * columns. + * + * @phpstan-type Column array{ name: string|null, type: non-empty-string, optional: bool } + * @phpstan-type Columns array{ columns: list, complete: bool } + * @phpstan-type Token array{ text: string, offset: int } + * @phpstan-import-type Column from WpdbSchema as SchemaColumn + */ +final class WpdbSelectParser { + + /** + * Keywords which end the select list or the `FROM` clause. + */ + private const CLAUSE_KEYWORDS = array( 'FROM', 'WHERE', 'GROUP', 'HAVING', 'WINDOW', 'ORDER', 'LIMIT', 'FOR', 'INTO', 'LOCK', 'UNION', 'EXCEPT', 'INTERSECT', ';' ); + + /** + * Keywords which start a join in the `FROM` clause. + */ + private const JOIN_KEYWORDS = array( 'JOIN', 'INNER', 'CROSS', 'LEFT', 'RIGHT', 'OUTER', 'NATURAL', 'STRAIGHT_JOIN' ); + + /** + * Modifiers which may follow `SELECT`. + */ + private const SELECT_MODIFIERS = array( 'ALL', 'DISTINCT', 'DISTINCTROW', 'HIGH_PRIORITY', 'STRAIGHT_JOIN', 'SQL_SMALL_RESULT', 'SQL_BIG_RESULT', 'SQL_BUFFER_RESULT', 'SQL_NO_CACHE', 'SQL_CACHE', 'SQL_CALC_FOUND_ROWS' ); + + /** + * Keywords which can end an expression, and so are not an alias following one. + */ + private const NON_ALIAS_KEYWORDS = array( 'END', 'NULL', 'TRUE', 'FALSE', 'ASC', 'DESC', 'DISTINCT' ); + + /** + * Schema of the core tables. + * + * @var WpdbSchema + */ + private WpdbSchema $schema; + + /** + * Parsed queries, keyed by query. + * + * @var array, complete: bool }|null> + * @phpstan-var array + */ + private array $cache = array(); + + /** + * Constructor. + * + * @param WpdbSchema $schema Schema of the core tables. + */ + public function __construct( WpdbSchema $schema ) { + $this->schema = $schema; + } + + /** + * Gets the columns a query returns. + * + * @param string $query Query, as reconstructed by `WpdbQueryVisitor`. + * @return array{ columns: list, complete: bool }|null { + * Columns, or null if the query is not a `SELECT` query this can read. + * + * @type list $columns { + * Columns, in order. + * + * @type string|null $name Column name, or null if unknown. + * @type non-empty-string $type PHPDoc type of the column's values. + * @type bool $optional Whether the column is only present on some sites. + * } + * @type bool $complete Whether the columns are all known. If not, more follow. + * } + * @phpstan-return Columns|null + */ + public function parse( string $query ): ?array { + if ( ! array_key_exists( $query, $this->cache ) ) { + $this->cache[ $query ] = $this->parse_uncached( $query ); + } + return $this->cache[ $query ]; + } + + /** + * Gets the columns a query returns, without the cache. + * + * @param string $query Query. + * @return array|null Columns, or null if the query is not a `SELECT` query this can read. + * @phpstan-return Columns|null + */ + private function parse_uncached( string $query ): ?array { + $tokens = self::tokenize( $query ); + $count = count( $tokens ); + + if ( 0 === $count || 'SELECT' !== strtoupper( $tokens[0]['text'] ) ) { + return null; + } + + $i = 1; + while ( $i < $count && in_array( strtoupper( $tokens[ $i ]['text'] ), self::SELECT_MODIFIERS, true ) ) { + ++$i; + } + + // Split the select list into its expressions. + $items = array(); + $item = array(); + $depth = 0; + for ( ; $i < $count; $i++ ) { + $text = $tokens[ $i ]['text']; + if ( 0 === $depth && ( ',' === $text || in_array( strtoupper( $text ), self::CLAUSE_KEYWORDS, true ) ) ) { + if ( ',' !== $text ) { + break; + } + $items[] = $item; + $item = array(); + continue; + } + $depth += self::get_depth_change( $text ); + $item[] = $tokens[ $i ]; + } + $items[] = $item; + + $tables = $this->parse_from( $tokens, $i ); + if ( null === $tables ) { + return null; + } + + $columns = array(); + foreach ( $items as $item ) { + $item_columns = $this->get_item_columns( $item, $tables, $query ); + if ( null === $item_columns ) { + return array( + 'columns' => $columns, + 'complete' => false, + ); + } + foreach ( $item_columns as $column ) { + $columns[] = $column; + } + } + + return array( + 'columns' => $columns, + 'complete' => true, + ); + } + + /** + * Reads the tables in the `FROM` clause. + * + * @param list $tokens Tokens of the query. + * @param int $i Index of the token ending the select list. + * @return array|null Table names, by `wpdb` property name or null if not a core table, keyed + * by the lowercase alias or name they are referred to by. Null if the query + * is a union, whose column types this does not read. + * @phpstan-param list $tokens + */ + private function parse_from( array $tokens, int $i ): ?array { + $count = count( $tokens ); + + // A union's columns may take their values from any of its queries. + $depth = 0; + for ( $j = $i; $j < $count; $j++ ) { + $depth += self::get_depth_change( $tokens[ $j ]['text'] ); + if ( 0 === $depth && in_array( strtoupper( $tokens[ $j ]['text'] ), array( 'UNION', 'EXCEPT', 'INTERSECT' ), true ) ) { + return null; + } + } + + $tables = array(); + if ( $i >= $count || 'FROM' !== strtoupper( $tokens[ $i ]['text'] ) ) { + return $tables; + } + + $expect_table = true; + $depth = 0; + for ( ++$i; $i < $count; $i++ ) { + $text = $tokens[ $i ]['text']; + $upper = strtoupper( $text ); + + if ( 0 === $depth && in_array( $upper, self::CLAUSE_KEYWORDS, true ) ) { + break; + } + + if ( 0 === $depth && ( ',' === $text || in_array( $upper, self::JOIN_KEYWORDS, true ) ) ) { + $expect_table = true; + continue; + } + + if ( 0 === $depth && $expect_table ) { + $expect_table = false; + + if ( '(' === $text ) { + // A derived table, or a parenthesized join. Its columns are unknown, unless they are qualified. + $name = null; + $nested = 0; + for ( ; $i < $count; $i++ ) { + $nested += self::get_depth_change( $tokens[ $i ]['text'] ); + if ( 0 === $nested ) { + break; + } + } + $key = ''; + } else { + $name = null; + if ( preg_match( '/^\{wpdb:(\w+)\}$/', $text, $match ) && $this->schema->has_table( $match[1] ) ) { + $name = $match[1]; + } + $key = strtolower( self::unquote( $text ) ); + } + + // The alias, if any. + $next = $tokens[ $i + 1 ]['text'] ?? ''; + if ( 'AS' === strtoupper( $next ) ) { + $i += 1; + $next = $tokens[ $i + 1 ]['text'] ?? ''; + } + if ( self::is_identifier( $next ) && ! in_array( strtoupper( $next ), array_merge( self::CLAUSE_KEYWORDS, self::JOIN_KEYWORDS, array( 'ON', 'USING', 'USE', 'IGNORE', 'FORCE', 'PARTITION' ) ), true ) ) { + $key = strtolower( self::unquote( $next ) ); + $i += 1; + } + + $tables[ $key ] = $name; + continue; + } + + $depth += self::get_depth_change( $text ); + } + + return $tables; + } + + /** + * Gets the columns of one expression in the select list. + * + * @param list $item Tokens of the expression, with its alias. + * @param array $tables Tables in the `FROM` clause. + * @param string $query Query. + * @return list|null Columns, or null if unknown. + * @phpstan-param list $item + * @phpstan-return list|null + */ + private function get_item_columns( array $item, array $tables, string $query ): ?array { + $count = count( $item ); + if ( 0 === $count ) { + return null; + } + + // An unknown part outside any parentheses could be any number of columns. + $depth = 0; + foreach ( $item as $token ) { + if ( 0 === $depth && WpdbQueryVisitor::UNKNOWN === $token['text'] ) { + return null; + } + $depth += self::get_depth_change( $token['text'] ); + } + + // The alias, if any. + $alias = null; + if ( $count >= 3 && 'AS' === strtoupper( $item[ $count - 2 ]['text'] ) && self::is_identifier( $item[ $count - 1 ]['text'] ) ) { + $alias = self::unquote( $item[ $count - 1 ]['text'] ); + $item = array_slice( $item, 0, $count - 2 ); + } elseif ( + $count >= 2 + && self::is_identifier( $item[ $count - 1 ]['text'] ) + && ! in_array( strtoupper( $item[ $count - 1 ]['text'] ), self::NON_ALIAS_KEYWORDS, true ) + && ( ')' === $item[ $count - 2 ]['text'] || self::is_identifier( $item[ $count - 2 ]['text'] ) || self::is_literal( $item[ $count - 2 ]['text'] ) ) + ) { + $alias = self::unquote( $item[ $count - 1 ]['text'] ); + $item = array_slice( $item, 0, $count - 1 ); + } + + $texts = array_column( $item, 'text' ); + $count = count( $texts ); + + // A `*` or `alias.*`. + if ( array( '*' ) === $texts || ( 3 === $count && '.' === $texts[1] && '*' === $texts[2] ) ) { + $star_tables = 1 === $count ? array_values( $tables ) : array( $tables[ strtolower( self::unquote( $texts[0] ) ) ] ?? null ); + if ( array() === $star_tables ) { + return null; + } + $columns = array(); + foreach ( $star_tables as $table ) { + if ( null === $table ) { + return null; + } + foreach ( $this->schema->get_columns( $table ) as $column ) { + $columns[] = $column; + } + } + return $columns; + } + + // A column reference. + $column_ref = self::get_column_reference( $texts ); + if ( null !== $column_ref ) { + list( $qualifier, $name ) = $column_ref; + $column = $this->find_column( $tables, $qualifier, $name ); + return array( + array( + 'name' => $alias ?? $name, + 'type' => null !== $column ? $column['type'] : 'string|null', + 'optional' => null !== $column && $column['optional'], + ), + ); + } + + // Otherwise MySQL names the column by the text of its expression. + if ( null === $alias ) { + $last = end( $item ); + $text = (string) substr( $query, $item[0]['offset'], $last['offset'] + strlen( $last['text'] ) - $item[0]['offset'] ); + $alias = false === strpos( $text, '{' ) ? $text : null; + } + + return array( + array( + 'name' => $alias, + 'type' => $this->get_expression_type( $texts, $tables ), + 'optional' => false, + ), + ); + } + + /** + * Gets the type of the values of an expression which is not a column reference. + * + * @param list $texts Tokens of the expression. + * @param array $tables Tables in the `FROM` clause. + * @return non-empty-string PHPDoc type. + */ + private function get_expression_type( array $texts, array $tables ): string { + $count = count( $texts ); + + if ( 1 === $count && preg_match( '/^-?\d+$/', $texts[0] ) ) { + return "'" . $texts[0] . "'"; + } + if ( 1 === $count && preg_match( "/^'([\\w .:-]*)'$/", $texts[0], $match ) ) { + return "'" . $match[1] . "'"; + } + + // A function call, like `COUNT( DISTINCT ID )`. + if ( $count >= 3 && self::is_identifier( $texts[0] ) && '(' === $texts[1] && ')' === $texts[ $count - 1 ] ) { + // The parentheses must be those of the one call, not `COUNT(a) + (b)`. + $depth = 0; + for ( $i = 1; $i < $count - 1; $i++ ) { + $depth += self::get_depth_change( $texts[ $i ] ); + if ( 0 === $depth ) { + return 'string|null'; + } + } + + $arguments = array_slice( $texts, 2, $count - 3 ); + switch ( strtoupper( $texts[0] ) ) { + case 'COUNT': + return 'decimal-int-string'; + case 'SUM': + case 'AVG': + return 'numeric-string|null'; + case 'MIN': + case 'MAX': + if ( isset( $arguments[0] ) && 'DISTINCT' === strtoupper( $arguments[0] ) ) { + $arguments = array_slice( $arguments, 1 ); + } + $column_ref = self::get_column_reference( $arguments ); + $column = null !== $column_ref ? $this->find_column( $tables, $column_ref[0], $column_ref[1] ) : null; + if ( null !== $column ) { + return '|null' === substr( $column['type'], -5 ) ? $column['type'] : $column['type'] . '|null'; + } + return 'string|null'; + } + } + + return 'string|null'; + } + + /** + * Finds a column of a core table. + * + * @param array $tables Tables in the `FROM` clause. + * @param string|null $qualifier Lowercase alias or name of the table, or null if not qualified. + * @param string $name Column name. + * @return array{ name: non-empty-string, type: non-empty-string, optional: bool }|null Column, or null if unknown. + * @phpstan-return SchemaColumn|null + */ + private function find_column( array $tables, ?string $qualifier, string $name ): ?array { + if ( null !== $qualifier ) { + $table = $tables[ $qualifier ] ?? null; + return null !== $table ? $this->schema->get_column( $table, $name ) : null; + } + + foreach ( $tables as $table ) { + $column = null !== $table ? $this->schema->get_column( $table, $name ) : null; + if ( null !== $column ) { + return $column; + } + } + return null; + } + + /** + * Gets the qualifier and name of a column reference, like `p.ID` or `ID`. + * + * @param list $texts Tokens of an expression. + * @return array{ 0: string|null, 1: string }|null Lowercase qualifier, or null if none, and column name. Null if + * the expression is not a column reference. + */ + private static function get_column_reference( array $texts ): ?array { + $count = count( $texts ); + if ( 1 === $count && self::is_identifier( $texts[0] ) && ! self::is_keyword_value( $texts[0] ) ) { + return array( null, self::unquote( $texts[0] ) ); + } + if ( 3 === $count && self::is_identifier( $texts[0] ) && '.' === $texts[1] && self::is_identifier( $texts[2] ) ) { + return array( strtolower( self::unquote( $texts[0] ) ), self::unquote( $texts[2] ) ); + } + return null; + } + + /** + * Splits a query into tokens, leaving out whitespace and comments. + * + * @param string $query Query. + * @return list + * @phpstan-return list + */ + private static function tokenize( string $query ): array { + preg_match_all( + '/\s+|--[^\n]*|\/\*.*?\*\/|\'(?:[^\'\\\\]|\\\\.|\'\')*\'|"(?:[^"\\\\]|\\\\.|"")*"|`[^`]*`|\{[^{}]*\}|\d+(?:\.\d+)?|[\w$]+|<=>|[<>!]=|<>|\|\||&&|./s', + $query, + $matches, + PREG_OFFSET_CAPTURE + ); + + $tokens = array(); + foreach ( $matches[0] as $match ) { + list( $text, $offset ) = $match; + if ( '' === trim( $text ) || 0 === strpos( $text, '--' ) || 0 === strpos( $text, '/*' ) ) { + continue; + } + $tokens[] = array( + 'text' => $text, + 'offset' => $offset, + ); + } + return $tokens; + } + + /** + * Gets how much a token changes the depth of parentheses. + * + * @param string $text Token. + * @return int + */ + private static function get_depth_change( string $text ): int { + if ( '(' === $text ) { + return 1; + } + if ( ')' === $text ) { + return -1; + } + return 0; + } + + /** + * Determines whether a token is an identifier: a name, a backtick-quoted name, or a core table. + * + * The unknown placeholder `{?}` is not one. + * + * @param string $text Token. + * @return bool + */ + private static function is_identifier( string $text ): bool { + return (bool) preg_match( '/^(?:[A-Za-z_$][\w$]*|`[^`]+`|\{wpdb:\w+\})$/', $text ); + } + + /** + * Determines whether a token is a literal: a number or a quoted string. + * + * @param string $text Token. + * @return bool + */ + private static function is_literal( string $text ): bool { + return (bool) preg_match( '/^(?:\d|\'|")/', $text ); + } + + /** + * Determines whether a token is a keyword which is a value, rather than a column name. + * + * @param string $text Token. + * @return bool + */ + private static function is_keyword_value( string $text ): bool { + return in_array( strtoupper( $text ), array( 'NULL', 'TRUE', 'FALSE', 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_USER' ), true ); + } + + /** + * Removes backticks around an identifier. + * + * @param string $text Identifier. + * @return string + */ + private static function unquote( string $text ): string { + if ( strlen( $text ) >= 2 && '`' === $text[0] && '`' === substr( $text, -1 ) ) { + return substr( $text, 1, -1 ); + } + return $text; + } +} diff --git a/tests/phpstan/base.neon b/tests/phpstan/base.neon index 1c102ca47e7da..1cd68fc324b6a 100644 --- a/tests/phpstan/base.neon +++ b/tests/phpstan/base.neon @@ -45,6 +45,20 @@ services: tags: - phpstan.broker.dynamicFunctionReturnTypeExtension + # Reconstructs the text of the query passed to each wpdb query method, following + # the variables it is built up in. See tests/phpstan/WpdbQueryVisitor.php. + - + class: WordPress\PHPStan\WpdbQueryVisitor + tags: + - phpstan.parser.richParserNodeVisitor + + # Types the results of wpdb::get_var(), get_row(), get_col() and get_results() + # from the columns their query selects, typed from the core database schema. + - + class: WordPress\PHPStan\WpdbQueryDynamicMethodReturnTypeExtension + tags: + - phpstan.broker.dynamicMethodReturnTypeExtension + # Enforces that every hook invocation is preceded by a documenting docblock or # a valid "This filter is documented in " reference comment. - @@ -305,6 +319,10 @@ parameters: - ApplyFiltersDynamicFunctionReturnTypeExtension.php - HookDocumentationRule.php - HookParamCountRule.php + - WpdbQueryDynamicMethodReturnTypeExtension.php + - WpdbQueryVisitor.php + - WpdbSchema.php + - WpdbSelectParser.php bootstrapFiles: - bootstrap.php scanFiles: diff --git a/tests/phpstan/baselines/argument.type.neon b/tests/phpstan/baselines/argument.type.neon index 7d4b6aa03dccb..5fc1cfbf80172 100644 --- a/tests/phpstan/baselines/argument.type.neon +++ b/tests/phpstan/baselines/argument.type.neon @@ -63,6 +63,11 @@ parameters: identifier: argument.type count: 1 path: ../../../src/wp-admin/edit.php + - + message: '#^Parameter \#1 \$number of function zeroise expects int, string\|null given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-admin/export.php - message: '#^Parameter \#1 \$attachment of function wp_get_attachment_id3_keys expects WP_Post, stdClass given\.$#' identifier: argument.type @@ -134,7 +139,17 @@ parameters: count: 2 path: ../../../src/wp-admin/includes/dashboard.php - - message: '#^Parameter \#1 \$callback of function array_map expects \(callable\(stdClass\)\: mixed\)\|null, ''get_comment'' given\.$#' + message: '#^Parameter \#1 \$attachment_id of function wp_get_attachment_url expects int, string given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-admin/includes/export.php + - + message: '#^Parameter \#1 \$callback of function array_map expects \(callable\(object\{comment_ID\: decimal\-int\-string, comment_post_ID\: decimal\-int\-string, comment_author\: string, comment_author_email\: string, comment_author_url\: string, comment_author_IP\: string, comment_date\: non\-falsy\-string, comment_date_gmt\: non\-falsy\-string, comment_content\: string, comment_karma\: decimal\-int\-string, comment_approved\: string, comment_agent\: string, comment_type\: string, comment_parent\: decimal\-int\-string, user_id\: decimal\-int\-string\}&stdClass\)\: mixed\)\|null, ''get_comment'' given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-admin/includes/export.php + - + message: '#^Parameter \#1 \$post_id of function is_sticky expects int, string given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-admin/includes/export.php @@ -143,6 +158,11 @@ parameters: identifier: argument.type count: 1 path: ../../../src/wp-admin/includes/export.php + - + message: '#^Parameter \#1 \$user_id of function get_userdata expects int, string given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-admin/includes/export.php - message: '#^Parameter \#2 \$callback of function add_filter expects callable\(\)\: mixed, ''wxr_filter_postmeta'' given\.$#' identifier: argument.type @@ -198,6 +218,11 @@ parameters: identifier: argument.type count: 3 path: ../../../src/wp-admin/includes/media.php + - + message: '#^Parameter \#1 \$number of function zeroise expects int, string\|null given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-admin/includes/media.php - message: '#^Parameter \#1 \$post_id of function get_media_items expects int, null given\.$#' identifier: argument.type @@ -209,12 +234,12 @@ parameters: count: 1 path: ../../../src/wp-admin/includes/menu.php - - message: '#^Parameter \#1 \$link_id of function wp_delete_link expects int, string\|null given\.$#' + message: '#^Parameter \#1 \$link_id of function wp_delete_link expects int, string given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-admin/includes/ms.php - - message: '#^Parameter \#1 \$post_id of function wp_delete_post expects int, string\|null given\.$#' + message: '#^Parameter \#1 \$post_id of function wp_delete_post expects int, string given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-admin/includes/ms.php @@ -224,7 +249,7 @@ parameters: count: 1 path: ../../../src/wp-admin/includes/ms.php - - message: '#^Parameter \#1 \$post_id of function wp_delete_post expects int, string\|null given\.$#' + message: '#^Parameter \#1 \$post_id of function wp_delete_post expects int, string given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-admin/includes/nav-menu.php @@ -283,6 +308,11 @@ parameters: identifier: argument.type count: 3 path: ../../../src/wp-admin/includes/template.php + - + message: '#^Parameter \#2 \$parent_page of function parent_dropdown expects int, string given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-admin/includes/template.php - message: '#^Parameter \#2 \$title of function add_meta_box expects string, null given\.$#' identifier: argument.type @@ -298,28 +328,58 @@ parameters: identifier: argument.type count: 1 path: ../../../src/wp-admin/includes/update-core.php + - + message: '#^Parameter \#1 \$attachment_id of function update_attached_file expects int, string given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-admin/includes/upgrade.php + - + message: '#^Parameter \#1 \$comment_id of function wp_delete_comment expects int\|WP_Comment, string\|null given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-admin/includes/upgrade.php + - + message: '#^Parameter \#1 \$post of function get_permalink expects int\|WP_Post, string given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-admin/includes/upgrade.php + - + message: '#^Parameter \#1 \$post_id of function get_post_meta expects int, string given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-admin/includes/upgrade.php - message: '#^Parameter \#1 \$timestamp of function wp_schedule_event expects int, float given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-admin/includes/upgrade.php - - message: '#^Parameter \#1 \$bookmark_id of function clean_bookmark_cache expects int, string\|null given\.$#' + message: '#^Parameter \#1 \$user_id of function get_user_meta expects int, string given\.$#' + identifier: argument.type + count: 2 + path: ../../../src/wp-admin/includes/upgrade.php + - + message: '#^Parameter \#1 \$user_id of function update_user_meta expects int, string given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-admin/includes/upgrade.php + - + message: '#^Parameter \#1 \$bookmark_id of function clean_bookmark_cache expects int, string given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-admin/includes/user.php - - message: '#^Parameter \#1 \$link_id of function wp_delete_link expects int, string\|null given\.$#' + message: '#^Parameter \#1 \$link_id of function wp_delete_link expects int, string given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-admin/includes/user.php - - message: '#^Parameter \#1 \$post of function clean_post_cache expects int\|WP_Post, string\|null given\.$#' + message: '#^Parameter \#1 \$post of function clean_post_cache expects int\|WP_Post, string given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-admin/includes/user.php - - message: '#^Parameter \#1 \$post_id of function wp_delete_post expects int, string\|null given\.$#' + message: '#^Parameter \#1 \$post_id of function wp_delete_post expects int, string given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-admin/includes/user.php @@ -653,6 +713,11 @@ parameters: identifier: argument.type count: 1 path: ../../../src/wp-includes/blocks.php + - + message: '#^Parameter \#1 \$object_ids of function wp_get_object_terms expects array\\|int, string given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-includes/bookmark.php - message: '#^Parameter \#2 \$callback of function preg_replace_callback expects callable\(array\\)\: string, ''lowercase_octets'' given\.$#' identifier: argument.type @@ -724,7 +789,12 @@ parameters: count: 1 path: ../../../src/wp-includes/class-wp-query.php - - message: '#^Parameter \#1 \$pages of function get_page_hierarchy expects array\, list\\|null given\.$#' + message: '#^Parameter \#1 \$page of function get_page_uri expects int\|object, string given\.$#' + identifier: argument.type + count: 1 + path: ../../../src/wp-includes/class-wp-rewrite.php + - + message: '#^Parameter \#1 \$pages of function get_page_hierarchy expects array\, \(list\\)\|null given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-includes/class-wp-rewrite.php @@ -878,6 +948,16 @@ parameters: identifier: argument.type count: 2 path: ../../../src/wp-includes/general-template.php + - + message: '#^Parameter \#1 \$year of function get_month_link expects int\|false, string\|null given\.$#' + identifier: argument.type + count: 2 + path: ../../../src/wp-includes/general-template.php + - + message: '#^Parameter \#2 \$month of function get_month_link expects int\|false, string\|null given\.$#' + identifier: argument.type + count: 2 + path: ../../../src/wp-includes/general-template.php - message: '#^Parameter \#2 \$replace of function str_replace expects array\\|string, int\<1, max\> given\.$#' identifier: argument.type @@ -924,12 +1004,12 @@ parameters: count: 1 path: ../../../src/wp-includes/media.php - - message: '#^Parameter \#2 \$callback of function array_walk expects callable\(non\-empty\-string\|null, int\<0, max\>\)\: mixed, ''clean_bookmark_cache'' given\.$#' + message: '#^Parameter \#2 \$callback of function array_walk expects callable\(decimal\-int\-string, int\<0, max\>\)\: mixed, ''clean_bookmark_cache'' given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-includes/ms-functions.php - - message: '#^Parameter \#2 \$callback of function array_walk expects callable\(non\-empty\-string\|null, int\<0, max\>\)\: mixed, ''clean_post_cache'' given\.$#' + message: '#^Parameter \#2 \$callback of function array_walk expects callable\(decimal\-int\-string, int\<0, max\>\)\: mixed, ''clean_post_cache'' given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-includes/ms-functions.php @@ -1014,22 +1094,22 @@ parameters: count: 1 path: ../../../src/wp-includes/post-template.php - - message: '#^Parameter \#1 \$comment_id of function wp_delete_comment expects int\|WP_Comment, string\|null given\.$#' + message: '#^Parameter \#1 \$comment_id of function wp_delete_comment expects int\|WP_Comment, string given\.$#' identifier: argument.type count: 2 path: ../../../src/wp-includes/post.php - - message: '#^Parameter \#1 \$post of function clean_post_cache expects int\|WP_Post, stdClass given\.$#' + message: '#^Parameter \#1 \$post of function clean_post_cache expects int\|WP_Post, object\{ID\: string, post_author\: string, post_date\: string, post_date_gmt\: string, post_content\: string, post_title\: string, post_excerpt\: string, post_status\: string, comment_status\: string, ping_status\: string, post_password\: string, post_name\: string, to_ping\: string, pinged\: string, post_modified\: string, post_modified_gmt\: string, post_content_filtered\: string, post_parent\: string, guid\: string, menu_order\: string, post_type\: string, post_mime_type\: string, comment_count\: string\}&stdClass given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-includes/post.php - - message: '#^Parameter \#1 \$post of function get_post expects int\|decimal\-int\-string\|WP_Post\|null, stdClass given\.$#' + message: '#^Parameter \#1 \$post of function get_post expects int\|decimal\-int\-string\|WP_Post\|null, object\{ID\: decimal\-int\-string, post_author\: decimal\-int\-string, post_date\: non\-falsy\-string, post_date_gmt\: non\-falsy\-string, post_content\: string, post_title\: string, post_excerpt\: string, post_status\: string, comment_status\: string, ping_status\: string, post_password\: string, post_name\: string, to_ping\: string, pinged\: string, post_modified\: non\-falsy\-string, post_modified_gmt\: non\-falsy\-string, post_content_filtered\: string, post_parent\: decimal\-int\-string, guid\: string, menu_order\: decimal\-int\-string, post_type\: string, post_mime_type\: string, comment_count\: decimal\-int\-string\}&stdClass given\.$#' identifier: argument.type count: 2 path: ../../../src/wp-includes/post.php - - message: '#^Parameter \#1 \$post_id of function wp_delete_post expects int, string\|null given\.$#' + message: '#^Parameter \#1 \$post_id of function wp_delete_post expects int, string given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-includes/post.php @@ -1039,7 +1119,7 @@ parameters: count: 1 path: ../../../src/wp-includes/post.php - - message: '#^Parameter \#1 \$revision of function wp_delete_post_revision expects int\|WP_Post, string\|null given\.$#' + message: '#^Parameter \#1 \$revision of function wp_delete_post_revision expects int\|WP_Post, string given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-includes/post.php @@ -1164,22 +1244,22 @@ parameters: count: 1 path: ../../../src/wp-includes/script-loader.php - - message: '#^Parameter \#1 \$object_id of function wp_remove_object_terms expects int, string\|null given\.$#' + message: '#^Parameter \#1 \$object_id of function wp_remove_object_terms expects int, string given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-includes/taxonomy.php - - message: '#^Parameter \#1 \$object_id of function wp_set_object_terms expects int, string\|null given\.$#' + message: '#^Parameter \#1 \$object_id of function wp_set_object_terms expects int, string given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-includes/taxonomy.php - - message: '#^Parameter \#1 \$object_ids of function wp_get_object_terms expects array\\|int, string\|null given\.$#' + message: '#^Parameter \#1 \$object_ids of function wp_get_object_terms expects array\\|int, string given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-includes/taxonomy.php - - message: '#^Parameter \#1 \$post_id of function update_post_meta expects int, string\|null given\.$#' + message: '#^Parameter \#1 \$post_id of function update_post_meta expects int, string given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-includes/taxonomy.php From bbaf0ebd62e2231a9a144793440231edbf669124 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Wed, 25 Nov 2026 14:48:37 -0800 Subject: [PATCH 02/21] Code Quality: Remove `@var` tags made redundant by the wpdb query types. The PHPStan extension for `wpdb` query methods now derives these types from the columns each query selects, as precisely or more so than the tags did. For example, the rows of `SELECT *` queries now have `decimal-int-string` for integer columns and `non-falsy-string` for datetime columns. The `@var` tag in `WP_Term_Query::get_terms()` stays, since its query is in `$this->request`, whose text is not known, and since the tag deliberately excludes null. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- src/wp-includes/class-wp-comment.php | 1 - src/wp-includes/ms-functions.php | 1 - src/wp-includes/post.php | 1 - .../rest-api/endpoints/class-wp-rest-comments-controller.php | 2 -- src/wp-includes/taxonomy.php | 1 - 5 files changed, 6 deletions(-) diff --git a/src/wp-includes/class-wp-comment.php b/src/wp-includes/class-wp-comment.php index 7ba2ff46dcc84..5454db3f253e2 100644 --- a/src/wp-includes/class-wp-comment.php +++ b/src/wp-includes/class-wp-comment.php @@ -268,7 +268,6 @@ public static function get_instance( $id ) { // A cached value that is not usable as a comment is treated as a cache miss. if ( ! is_object( $_comment ) || ! isset( $_comment->comment_ID ) ) { - /** @var object{ comment_ID: string, comment_post_ID: string, comment_author: string, comment_author_email: string, comment_author_url: string, comment_author_IP: string, comment_date: string, comment_date_gmt: string, comment_content: string, comment_karma: string, comment_approved: string, comment_agent: string, comment_type: string, comment_parent: string, user_id: string }|null $_comment */ $_comment = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment_id ) ); if ( ! $_comment ) { diff --git a/src/wp-includes/ms-functions.php b/src/wp-includes/ms-functions.php index 17e7041b883cf..3a6d3eee27961 100644 --- a/src/wp-includes/ms-functions.php +++ b/src/wp-includes/ms-functions.php @@ -1208,7 +1208,6 @@ function wpmu_activate_signup( ) { global $wpdb; - /** @var object{ signup_id: string, domain: string, path: string, title: string, user_login: string, user_email: string, registered: string, activated: string, active: string, activation_key: string, meta: string|null }|null $signup */ $signup = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->signups WHERE activation_key = %s", $key ) ); if ( empty( $signup ) ) { diff --git a/src/wp-includes/post.php b/src/wp-includes/post.php index 6d42c97836dea..53c13cf624072 100644 --- a/src/wp-includes/post.php +++ b/src/wp-includes/post.php @@ -6562,7 +6562,6 @@ function get_page_by_path( $page_path, $output = OBJECT, $post_type = 'page' ) { post_status IN ('draft', 'pending', 'auto-draft') ASC, ID ASC "; - /** @var array $pages */ $pages = $wpdb->get_results( $sql, OBJECT_K ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- The escaping has been applied above via esc_sql(). $revparts = array_reverse( $parts ); diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php index 3bb44059052eb..62cab7ad7daa7 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php @@ -2433,7 +2433,6 @@ protected function prefetch_reaction_summaries( $note_ids ) { // Query 1: Get aggregated counts per emoji per note. $query = "SELECT r.comment_parent, r.comment_content, COUNT(*) AS reaction_count $from $where GROUP BY r.comment_parent, r.comment_content"; - /** @var list|null $counts */ $counts = $wpdb->get_results( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- It is prepared above. // Query 2: Get the current user's own reaction IDs (if logged in). @@ -2441,7 +2440,6 @@ protected function prefetch_reaction_summaries( $note_ids ) { if ( $current_user_id ) { $query = "SELECT r.comment_ID, r.comment_parent, r.comment_content $from $where"; $query .= $wpdb->prepare( ' AND r.user_id = %d', $current_user_id ); - /** @var list|null $user_rows */ $user_rows = $wpdb->get_results( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- It is prepared above. if ( $user_rows ) { diff --git a/src/wp-includes/taxonomy.php b/src/wp-includes/taxonomy.php index 06d1d3581dd00..1d8c04de088e7 100644 --- a/src/wp-includes/taxonomy.php +++ b/src/wp-includes/taxonomy.php @@ -2768,7 +2768,6 @@ function wp_insert_term( $term, $taxonomy, $args = array() ) { do_action( 'edited_terms', $term_id, $taxonomy, $args ); } - /** @var decimal-int-string|null $tt_id */ $tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id ) ); if ( ! empty( $tt_id ) ) { From 3b04d5ebe980a3bc257629fa5f43ff2a363d64e4 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Wed, 25 Nov 2026 23:15:59 -0800 Subject: [PATCH 03/21] Fix phpcs alignment gripes --- .../endpoints/class-wp-rest-comments-controller.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php index 62cab7ad7daa7..bf0c77bb753fa 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php @@ -2432,14 +2432,14 @@ protected function prefetch_reaction_summaries( $note_ids ) { ); // Query 1: Get aggregated counts per emoji per note. - $query = "SELECT r.comment_parent, r.comment_content, COUNT(*) AS reaction_count $from $where GROUP BY r.comment_parent, r.comment_content"; + $query = "SELECT r.comment_parent, r.comment_content, COUNT(*) AS reaction_count $from $where GROUP BY r.comment_parent, r.comment_content"; $counts = $wpdb->get_results( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- It is prepared above. // Query 2: Get the current user's own reaction IDs (if logged in). $my_reactions = array(); if ( $current_user_id ) { - $query = "SELECT r.comment_ID, r.comment_parent, r.comment_content $from $where"; - $query .= $wpdb->prepare( ' AND r.user_id = %d', $current_user_id ); + $query = "SELECT r.comment_ID, r.comment_parent, r.comment_content $from $where"; + $query .= $wpdb->prepare( ' AND r.user_id = %d', $current_user_id ); $user_rows = $wpdb->get_results( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- It is prepared above. if ( $user_rows ) { From c31d7bf3266ae9ada8e328afdae12f08e54e07f1 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:04:03 -0800 Subject: [PATCH 04/21] Code Quality: Make outer-joined columns nullable in wpdb query types. A table on the outer side of a `LEFT JOIN` or `RIGHT JOIN` has no row to match for some rows of the result, so each of its columns is null there. `WpdbSelectParser` now records which tables these are, and adds null to the types of their columns, including those a `*` or `alias.*` expands to. `LEFT` and `RIGHT` are also functions, so they now only start a join when `JOIN` or `OUTER` follows, and not in an `ON` condition. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- tests/phpstan/WpdbSelectParser.php | 103 +++++++++++++++++++++++------ 1 file changed, 83 insertions(+), 20 deletions(-) diff --git a/tests/phpstan/WpdbSelectParser.php b/tests/phpstan/WpdbSelectParser.php index 1257f3fe48427..12cfdc422f8b1 100644 --- a/tests/phpstan/WpdbSelectParser.php +++ b/tests/phpstan/WpdbSelectParser.php @@ -20,7 +20,8 @@ * Each column is typed as follows: * * - A column of a core table, including each one a `*` or `alias.*` expands - * to, has the type `WpdbSchema` gives it. + * to, has the type `WpdbSchema` gives it, or null as well for a table on the + * outer side of a `LEFT JOIN` or `RIGHT JOIN`, which has no row to match. * - `COUNT()` is a `decimal-int-string`, `SUM()` and `AVG()` are a * `numeric-string` or null, and `MIN()` and `MAX()` of a core column are the * column's type or null. @@ -38,6 +39,7 @@ * @phpstan-type Column array{ name: string|null, type: non-empty-string, optional: bool } * @phpstan-type Columns array{ columns: list, complete: bool } * @phpstan-type Token array{ text: string, offset: int } + * @phpstan-type Table array{ name: string|null, nullable: bool } * @phpstan-import-type Column from WpdbSchema as SchemaColumn */ final class WpdbSelectParser { @@ -180,10 +182,14 @@ private function parse_uncached( string $query ): ?array { * * @param list $tokens Tokens of the query. * @param int $i Index of the token ending the select list. - * @return array|null Table names, by `wpdb` property name or null if not a core table, keyed - * by the lowercase alias or name they are referred to by. Null if the query - * is a union, whose column types this does not read. + * @return array|null Tables, keyed by the lowercase alias or + * name they are referred to by. Each has its + * `wpdb` property name, or null if not a core + * table, and whether its columns may be null + * from an outer join. Null if the query is a + * union, whose column types this does not read. * @phpstan-param list $tokens + * @phpstan-return array|null */ private function parse_from( array $tokens, int $i ): ?array { $count = count( $tokens ); @@ -203,6 +209,7 @@ private function parse_from( array $tokens, int $i ): ?array { } $expect_table = true; + $outer_join = null; $depth = 0; for ( ++$i; $i < $count; $i++ ) { $text = $tokens[ $i ]['text']; @@ -212,8 +219,19 @@ private function parse_from( array $tokens, int $i ): ?array { break; } + // `LEFT` and `RIGHT` are also functions, as in an `ON` condition. + if ( ( 'LEFT' === $upper || 'RIGHT' === $upper ) && ! in_array( strtoupper( $tokens[ $i + 1 ]['text'] ?? '' ), array( 'JOIN', 'OUTER' ), true ) ) { + $depth += self::get_depth_change( $text ); + continue; + } + if ( 0 === $depth && ( ',' === $text || in_array( $upper, self::JOIN_KEYWORDS, true ) ) ) { $expect_table = true; + if ( 'LEFT' === $upper || 'RIGHT' === $upper ) { + $outer_join = $upper; + } elseif ( ',' === $text ) { + $outer_join = null; + } continue; } @@ -250,7 +268,17 @@ private function parse_from( array $tokens, int $i ): ?array { $i += 1; } - $tables[ $key ] = $name; + // The table on the outer side of a join may have no row to match, which makes its columns null. + if ( 'RIGHT' === $outer_join ) { + foreach ( array_keys( $tables ) as $table_key ) { + $tables[ $table_key ]['nullable'] = true; + } + } + $tables[ $key ] = array( + 'name' => $name, + 'nullable' => 'LEFT' === $outer_join, + ); + $outer_join = null; continue; } @@ -263,11 +291,12 @@ private function parse_from( array $tokens, int $i ): ?array { /** * Gets the columns of one expression in the select list. * - * @param list $item Tokens of the expression, with its alias. - * @param array $tables Tables in the `FROM` clause. - * @param string $query Query. + * @param list $item Tokens of the expression, with its alias. + * @param array $tables Tables in the `FROM` clause. + * @param string $query Query. * @return list|null Columns, or null if unknown. * @phpstan-param list $item + * @phpstan-param array $tables * @phpstan-return list|null */ private function get_item_columns( array $item, array $tables, string $query ): ?array { @@ -311,11 +340,11 @@ private function get_item_columns( array $item, array $tables, string $query ): } $columns = array(); foreach ( $star_tables as $table ) { - if ( null === $table ) { + if ( null === $table || null === $table['name'] ) { return null; } - foreach ( $this->schema->get_columns( $table ) as $column ) { - $columns[] = $column; + foreach ( $this->schema->get_columns( $table['name'] ) as $column ) { + $columns[] = self::apply_nullable( $column, $table ); } } return $columns; @@ -354,9 +383,10 @@ private function get_item_columns( array $item, array $tables, string $query ): /** * Gets the type of the values of an expression which is not a column reference. * - * @param list $texts Tokens of the expression. - * @param array $tables Tables in the `FROM` clause. + * @param list $texts Tokens of the expression. + * @param array $tables Tables in the `FROM` clause. * @return non-empty-string PHPDoc type. + * @phpstan-param array $tables */ private function get_expression_type( array $texts, array $tables ): string { $count = count( $texts ); @@ -394,7 +424,7 @@ private function get_expression_type( array $texts, array $tables ): string { $column_ref = self::get_column_reference( $arguments ); $column = null !== $column_ref ? $this->find_column( $tables, $column_ref[0], $column_ref[1] ) : null; if ( null !== $column ) { - return '|null' === substr( $column['type'], -5 ) ? $column['type'] : $column['type'] . '|null'; + return self::add_null( $column['type'] ); } return 'string|null'; } @@ -406,27 +436,60 @@ private function get_expression_type( array $texts, array $tables ): string { /** * Finds a column of a core table. * - * @param array $tables Tables in the `FROM` clause. - * @param string|null $qualifier Lowercase alias or name of the table, or null if not qualified. - * @param string $name Column name. + * @param array $tables Tables in the `FROM` clause. + * @param string|null $qualifier Lowercase alias or name of the table, + * or null if not qualified. + * @param string $name Column name. * @return array{ name: non-empty-string, type: non-empty-string, optional: bool }|null Column, or null if unknown. + * @phpstan-param array $tables * @phpstan-return SchemaColumn|null */ private function find_column( array $tables, ?string $qualifier, string $name ): ?array { if ( null !== $qualifier ) { $table = $tables[ $qualifier ] ?? null; - return null !== $table ? $this->schema->get_column( $table, $name ) : null; + if ( null === $table || null === $table['name'] ) { + return null; + } + $column = $this->schema->get_column( $table['name'], $name ); + return null !== $column ? self::apply_nullable( $column, $table ) : null; } foreach ( $tables as $table ) { - $column = null !== $table ? $this->schema->get_column( $table, $name ) : null; + $column = null !== $table['name'] ? $this->schema->get_column( $table['name'], $name ) : null; if ( null !== $column ) { - return $column; + return self::apply_nullable( $column, $table ); } } return null; } + /** + * Makes a column's type nullable if its table is on the outer side of a join. + * + * @param array{ name: non-empty-string, type: non-empty-string, optional: bool } $column Column of a core table. + * @param array{ name: string|null, nullable: bool } $table Table the column is in. + * @return array{ name: non-empty-string, type: non-empty-string, optional: bool } Column. + * @phpstan-param SchemaColumn $column + * @phpstan-param Table $table + * @phpstan-return SchemaColumn + */ + private static function apply_nullable( array $column, array $table ): array { + if ( $table['nullable'] ) { + $column['type'] = self::add_null( $column['type'] ); + } + return $column; + } + + /** + * Adds null to a PHPDoc type. + * + * @param non-empty-string $type PHPDoc type. + * @return non-empty-string + */ + private static function add_null( string $type ): string { + return '|null' === substr( $type, -5 ) ? $type : $type . '|null'; + } + /** * Gets the qualifier and name of a column reference, like `p.ID` or `ID`. * From bb4e1a802894ecf0933f27d284ffaafb9b7594d9 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:05:21 -0800 Subject: [PATCH 05/21] Code Quality: Read quoted column aliases in wpdb query types. MySQL accepts a quoted string as a column alias, as in `SELECT TABLE_ROWS AS 'rows'` in `WP_Site_Health`, but `WpdbSelectParser` only took a name as one, and so named such a column by the whole text of the expression and its alias. It now reads a single- or double-quoted alias, with or without `AS`, and removes its quotes. Without `AS`, a quoted string following a string literal is not an alias, since MySQL joins the two strings. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- tests/phpstan/WpdbSelectParser.php | 42 +++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/tests/phpstan/WpdbSelectParser.php b/tests/phpstan/WpdbSelectParser.php index 12cfdc422f8b1..9d44cd5540895 100644 --- a/tests/phpstan/WpdbSelectParser.php +++ b/tests/phpstan/WpdbSelectParser.php @@ -314,18 +314,26 @@ private function get_item_columns( array $item, array $tables, string $query ): $depth += self::get_depth_change( $token['text'] ); } - // The alias, if any. - $alias = null; - if ( $count >= 3 && 'AS' === strtoupper( $item[ $count - 2 ]['text'] ) && self::is_identifier( $item[ $count - 1 ]['text'] ) ) { - $alias = self::unquote( $item[ $count - 1 ]['text'] ); + // The alias, if any, which may be a name or a quoted string. + $alias = null; + $last_text = $item[ $count - 1 ]['text']; + $previous = $count >= 2 ? $item[ $count - 2 ]['text'] : ''; + if ( $count >= 3 && 'AS' === strtoupper( $previous ) && ( self::is_identifier( $last_text ) || self::is_quoted_string( $last_text ) ) ) { + $alias = self::unquote( $last_text ); $item = array_slice( $item, 0, $count - 2 ); } elseif ( $count >= 2 - && self::is_identifier( $item[ $count - 1 ]['text'] ) - && ! in_array( strtoupper( $item[ $count - 1 ]['text'] ), self::NON_ALIAS_KEYWORDS, true ) - && ( ')' === $item[ $count - 2 ]['text'] || self::is_identifier( $item[ $count - 2 ]['text'] ) || self::is_literal( $item[ $count - 2 ]['text'] ) ) + && ( + // A string following a string literal is not an alias, but is joined to it. + ( self::is_quoted_string( $last_text ) && ( ')' === $previous || self::is_identifier( $previous ) ) ) + || ( + self::is_identifier( $last_text ) + && ! in_array( strtoupper( $last_text ), self::NON_ALIAS_KEYWORDS, true ) + && ( ')' === $previous || self::is_identifier( $previous ) || self::is_literal( $previous ) ) + ) + ) ) { - $alias = self::unquote( $item[ $count - 1 ]['text'] ); + $alias = self::unquote( $last_text ); $item = array_slice( $item, 0, $count - 1 ); } @@ -586,15 +594,29 @@ private static function is_keyword_value( string $text ): bool { } /** - * Removes backticks around an identifier. + * Determines whether a token is a quoted string, with single or double quotes. * - * @param string $text Identifier. + * @param string $text Token. + * @return bool + */ + private static function is_quoted_string( string $text ): bool { + return strlen( $text ) >= 2 && ( "'" === $text[0] || '"' === $text[0] ) && $text[0] === substr( $text, -1 ); + } + + /** + * Removes the backticks around an identifier, or the quotes around a string used as an alias. + * + * @param string $text Identifier or quoted string. * @return string */ private static function unquote( string $text ): string { if ( strlen( $text ) >= 2 && '`' === $text[0] && '`' === substr( $text, -1 ) ) { return substr( $text, 1, -1 ); } + if ( self::is_quoted_string( $text ) ) { + $quote = $text[0]; + return str_replace( array( $quote . $quote, '\\' . $quote, '\\\\' ), array( $quote, $quote, '\\' ), substr( $text, 1, -1 ) ); + } return $text; } } From 7919bdc3f4ac083062854d85beb163d584783d00 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:06:45 -0800 Subject: [PATCH 06/21] Code Quality: Treat `prepare()` placeholders as unknown values in wpdb query types. `WpdbQueryVisitor` replaced `$wpdb->prepare()` by its format, placeholders and all, so that a placeholder in the select list read as a column: for `SELECT %i FROM ...`, a column named `%i`, rather than whichever column the argument names. Each placeholder now becomes `{value}`, a single value whose text is not known, and each `%%` becomes `%`. `WpdbSelectParser` types such a value as `string|null`, and leaves its name unknown unless it has an alias. Unlike `{?}`, it is one column, so the columns after it stay known. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- tests/phpstan/WpdbQueryVisitor.php | 16 ++++++++++++++-- tests/phpstan/WpdbSelectParser.php | 7 ++++--- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/tests/phpstan/WpdbQueryVisitor.php b/tests/phpstan/WpdbQueryVisitor.php index f20f6b773b49f..24806f4a2b5f2 100644 --- a/tests/phpstan/WpdbQueryVisitor.php +++ b/tests/phpstan/WpdbQueryVisitor.php @@ -42,7 +42,9 @@ * - String literals, interpolation and concatenation are joined. * - A table property on `$wpdb`, like `$wpdb->posts`, becomes the placeholder * `{wpdb:posts}`, so that the query parser knows which table it names. - * - `$wpdb->prepare( $query, ... )` is replaced by its query. + * - `$wpdb->prepare( $query, ... )` is replaced by its query, with the + * placeholder `{value}` for each of its placeholders, like `%d` or `%i`, and + * `%` for each `%%`. * - A variable is replaced by the value assigned to it by the nearest preceding * `$var = ...;` statement, followed by any `$var .= ...;` statements after it. * The search walks back through the preceding statements, out through the @@ -75,6 +77,11 @@ final class WpdbQueryVisitor extends NodeVisitorAbstract { */ public const UNKNOWN = '{?}'; + /** + * Placeholder for a single value or identifier whose text is unknown, from a placeholder in a prepared query. + */ + public const VALUE = '{value}'; + /** * Methods of `wpdb` whose first parameter is a query to reconstruct. */ @@ -206,7 +213,12 @@ private function evaluate( Expr $expr, array $position, int $depth ): string { && isset( $expr->args[0] ) && $expr->args[0] instanceof Arg ) { - return $this->evaluate( $expr->args[0]->value, $position, $depth ); + // Each placeholder is a value, or for `%i` an identifier, which is not known. + return (string) preg_replace_callback( + '/%(?:%|(?:\d+\$)?[-+0 ]*(?:\'.)?\d*(?:\.\d+)?[dfFsi])/', + static fn ( array $matches ): string => '%%' === $matches[0] ? '%' : self::VALUE, + $this->evaluate( $expr->args[0]->value, $position, $depth ) + ); } if ( $expr instanceof Variable && is_string( $expr->name ) && $depth < self::MAX_DEPTH ) { diff --git a/tests/phpstan/WpdbSelectParser.php b/tests/phpstan/WpdbSelectParser.php index 9d44cd5540895..efae3ef7c2b72 100644 --- a/tests/phpstan/WpdbSelectParser.php +++ b/tests/phpstan/WpdbSelectParser.php @@ -15,7 +15,8 @@ * This is not a SQL parser. It reads only as much of the query as it needs: * the select list, and the tables named in the `FROM` clause with their * aliases. The query text is as reconstructed by `WpdbQueryVisitor`, where a - * core table is `{wpdb:
}` and an unknown part is `{?}`. + * core table is `{wpdb:
}`, an unknown part is `{?}`, and an unknown + * single value, from a placeholder, is `{value}`. * * Each column is typed as follows: * @@ -574,13 +575,13 @@ private static function is_identifier( string $text ): bool { } /** - * Determines whether a token is a literal: a number or a quoted string. + * Determines whether a token is a literal: a number, a quoted string, or a value from a placeholder. * * @param string $text Token. * @return bool */ private static function is_literal( string $text ): bool { - return (bool) preg_match( '/^(?:\d|\'|")/', $text ); + return WpdbQueryVisitor::VALUE === $text || (bool) preg_match( '/^(?:\d|\'|")/', $text ); } /** From ad2e08c57c8d91ce236c9b3cf2f7b3d30d707a7f Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:07:58 -0800 Subject: [PATCH 07/21] Code Quality: Type `ARRAY_N` rows with and without the multisite columns. The `spam` and `deleted` columns of the users table only exist on multisite, so on a single site each column after them in a row from `ARRAY_N` is two positions earlier. The extension typed such a row with those two columns as optional offsets, but each column after them at a fixed offset, which is only right on multisite. The values of a row are now typed in two variants, one with the multisite columns and one without, and an `ARRAY_N` row is the union of the two. The column index of `get_var()` and `get_col()` is typed from both variants too, which replaces stopping at the first such column, and so types the columns after it as well. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- ...bQueryDynamicMethodReturnTypeExtension.php | 71 ++++++++++--------- 1 file changed, 37 insertions(+), 34 deletions(-) diff --git a/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php index ffdc6b1241232..8c3b199b1837c 100644 --- a/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php +++ b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php @@ -183,7 +183,7 @@ public function getTypeFromMethodCall( MethodReflection $methodReflection, Metho * @return Type|null Type, or null if unknown. */ private function get_positional_value_type( array $columns, bool $complete, ?\PhpParser\Node\Expr $x, Scope $scope ): ?Type { - $positional = $this->get_positional_columns( $columns, $complete ); + $variants = self::get_row_variants( $columns ); $indexes = array( 0 ); if ( null !== $x ) { @@ -196,28 +196,30 @@ private function get_positional_value_type( array $columns, bool $complete, ?\Ph } if ( array() === $indexes ) { // Any column. - if ( count( $positional ) !== count( $columns ) || ! $complete ) { + if ( ! $complete ) { return null; } - $indexes = array_keys( $columns ); + $indexes = array_keys( $variants[0] ); } } $types = array(); foreach ( $indexes as $index ) { - if ( ! isset( $positional[ $index ] ) ) { - // Past the known columns, or an index with no column, for which the value is null. - if ( $complete && count( $positional ) === count( $columns ) ) { + foreach ( $variants as $variant ) { + if ( ! isset( $variant[ $index ] ) ) { + // Past the known columns, or an index with no column, for which the value is null. + if ( ! $complete ) { + return null; + } $types[] = new NullType(); continue; } - return null; - } - $type = $positional[ $index ]['type']; - $non_null = TypeCombinator::removeNull( $type ); - $types[] = TypeCombinator::intersect( $non_null, new StringType(), new AccessoryNonEmptyStringType() ); - if ( ! $type->isNull()->no() || ! $non_null->isSuperTypeOf( new ConstantStringType( '' ) )->no() ) { - $types[] = new NullType(); + $type = $variant[ $index ]; + $non_null = TypeCombinator::removeNull( $type ); + $types[] = TypeCombinator::intersect( $non_null, new StringType(), new AccessoryNonEmptyStringType() ); + if ( ! $type->isNull()->no() || ! $non_null->isSuperTypeOf( new ConstantStringType( '' ) )->no() ) { + $types[] = new NullType(); + } } } @@ -225,28 +227,25 @@ private function get_positional_value_type( array $columns, bool $complete, ?\Ph } /** - * Gets the columns whose positions are known. + * Gets the values of a row as a list, as `ARRAY_N` and the column index of `get_var()` and `get_col()` see them. * - * A column only present on some sites shifts the positions of those after it, and the columns after an unknown - * one are unknown. + * A column only present on some sites, like the multisite columns of the users table, shifts the positions of + * those after it. So there are two variants of the row, one with those columns and one without. They are taken to + * be all present or all absent together, as the multisite columns are. * - * @param list $columns Columns. - * @param bool $complete Whether the columns are all known. - * @return list Columns, from the first. + * @param list $columns Columns. + * @return non-empty-list> Types of the values, in each variant of the row. */ - private function get_positional_columns( array $columns, bool $complete ): array { - $positional = array(); - foreach ( $columns as $index => $column ) { - if ( $column['optional'] ) { - // Its own position is known, but whether it is there is not. - $is_last = ( count( $columns ) - 1 === $index ) && $complete; - if ( ! $is_last ) { - break; - } + private static function get_row_variants( array $columns ): array { + $with = array(); + $without = array(); + foreach ( $columns as $column ) { + $with[] = $column['type']; + if ( ! $column['optional'] ) { + $without[] = $column['type']; } - $positional[] = $column; } - return $positional; + return count( $with ) === count( $without ) ? array( $with ) : array( $with, $without ); } /** @@ -281,11 +280,15 @@ private function refine_rows( Type $declared, array $columns, bool $complete ): $list_row = null; if ( $complete ) { - $builder = ConstantArrayTypeBuilder::createEmpty(); - foreach ( $columns as $index => $column ) { - $builder->setOffsetValueType( new ConstantIntegerType( $index ), $column['type'], $column['optional'] ); + $list_rows = array(); + foreach ( self::get_row_variants( $columns ) as $variant ) { + $builder = ConstantArrayTypeBuilder::createEmpty(); + foreach ( $variant as $index => $type ) { + $builder->setOffsetValueType( new ConstantIntegerType( $index ), $type ); + } + $list_rows[] = $builder->getArray(); } - $list_row = $builder->getArray(); + $list_row = TypeCombinator::union( ...$list_rows ); } // `OBJECT_K` keys the rows by the first column's value, with null as ''. From 2dd2d5a1b5e4c1220e9f06f5dbf99570b630ad4e Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:08:51 -0800 Subject: [PATCH 08/21] Code Quality: Collapse duplicate column names in positional wpdb row types. `wpdb` makes an `ARRAY_N` row, and finds the value at the column index of `get_var()` and `get_col()`, from `array_values( get_object_vars( $row ) )`. The row object has one property for each column name, so a column with the name of an earlier one, like `term_id` in `SELECT t.*, tt.*`, replaces the earlier one's value in its position, and is not a value of its own. The extension counted each column in the select list instead, so typed such a row with too many values, and the values after a repeated name at the wrong index. The values of a row now have one per column name, with the type of the last column of that name, at the position of the first. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- ...bQueryDynamicMethodReturnTypeExtension.php | 35 +++++++++++++++---- 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php index 8c3b199b1837c..e8c4ee0a56252 100644 --- a/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php +++ b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php @@ -233,19 +233,42 @@ private function get_positional_value_type( array $columns, bool $complete, ?\Ph * those after it. So there are two variants of the row, one with those columns and one without. They are taken to * be all present or all absent together, as the multisite columns are. * + * The values are those of the row object's properties, so there is one for each column name: a later column with + * the name of an earlier one replaces its value, in its position. + * * @param list $columns Columns. * @return non-empty-list> Types of the values, in each variant of the row. */ private static function get_row_variants( array $columns ): array { - $with = array(); - $without = array(); + $with = self::get_row_values( $columns ); + $without = self::get_row_values( array_values( array_filter( $columns, static fn ( array $column ): bool => ! $column['optional'] ) ) ); + return count( $with ) === count( $without ) ? array( $with ) : array( $with, $without ); + } + + /** + * Gets the types of the values of a row, as `array_values( get_object_vars( $row ) )` gives them. + * + * A column whose name is unknown is taken to have a name of its own. + * + * @param list $columns Columns present in the row. + * @return list Types of the values. + */ + private static function get_row_values( array $columns ): array { + $values = array(); + $positions = array(); foreach ( $columns as $column ) { - $with[] = $column['type']; - if ( ! $column['optional'] ) { - $without[] = $column['type']; + $name = $column['name']; + if ( null !== $name && isset( $positions[ $name ] ) ) { + $values[ $positions[ $name ] ] = $column['type']; + continue; } + if ( null !== $name ) { + $positions[ $name ] = count( $values ); + } + $values[] = $column['type']; } - return count( $with ) === count( $without ) ? array( $with ) : array( $with, $without ); + // Replacing a value at its position keeps the keys sequential. + return array_values( $values ); } /** From 4fa83a92c05ecd022d7296ef13dfaa56fc54d4e6 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:09:44 -0800 Subject: [PATCH 09/21] Code Quality: Follow writes in enclosing conditions and loops for wpdb queries. In following a variable back to its value, `WpdbQueryVisitor` missed two kinds of write in the statements the query method call is in, and so typed the result from a value the variable no longer had: * An `if` the call is in was exempt from the check for writes, as only the branch the call is in has run, but its conditions have run too, as in `if ( $query = get_option( 'query' ) )`. * A loop whose condition the call is in, as in `while ( $wpdb->get_var( $sql ) )`, was not checked at all, though its body may have run before the condition, in an earlier iteration, or for a `do` loop, the first one. The conditions of an enclosing `if`, and the whole of a loop the call is in directly, are now checked for writes as well. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- tests/phpstan/WpdbQueryVisitor.php | 45 +++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/tests/phpstan/WpdbQueryVisitor.php b/tests/phpstan/WpdbQueryVisitor.php index 24806f4a2b5f2..ec14387dc8d1e 100644 --- a/tests/phpstan/WpdbQueryVisitor.php +++ b/tests/phpstan/WpdbQueryVisitor.php @@ -243,13 +243,7 @@ private function resolve_variable( string $name, array $position, int $depth ): for ( $level = count( $position ) - 1; $level >= 0; $level-- ) { list( $stmts, $index ) = $position[ $level ]; - /* - * The statement at an outer level is the block the position is in. A write to the variable anywhere in a - * loop may have run before the position, in an earlier iteration, and likewise in the try block for a - * position in a catch block, and so on. The exception is an `if`: of its branches, only the one the - * position is in has run. - */ - if ( count( $position ) - 1 !== $level && ! $stmts[ $index ] instanceof Stmt\If_ && $this->writes_variable( $stmts[ $index ], $name, false ) ) { + if ( $this->may_write_before( $stmts[ $index ], $name, count( $position ) - 1 === $level ) ) { return self::UNKNOWN; } @@ -286,6 +280,43 @@ private function resolve_variable( string $name, array $position, int $depth ): return self::UNKNOWN; } + /** + * Determines whether a statement the position is in may write to a variable before the position. + * + * A statement at an outer level is a block the position is in. A write to the variable anywhere in a loop may have + * run before the position, in an earlier iteration, and likewise in the try block for a position in a catch block, + * and so on. The exception is an `if`: of its branches, only the one the position is in has run, after the + * conditions. + * + * The innermost statement is the one the position is in directly, which runs before the position only where it is + * a loop, whose body may have run in an earlier iteration, or the conditions of an `if`. + * + * @param Node $stmt Statement. + * @param string $name Variable name. + * @param bool $innermost Whether the statement is the innermost one. + * @return bool + */ + private function may_write_before( Node $stmt, string $name, bool $innermost ): bool { + if ( $stmt instanceof Stmt\If_ ) { + $conditions = array( $stmt->cond ); + foreach ( $stmt->elseifs as $elseif ) { + $conditions[] = $elseif->cond; + } + foreach ( $conditions as $condition ) { + if ( $this->writes_variable( $condition, $name, false ) ) { + return true; + } + } + return false; + } + + $is_loop = $stmt instanceof Stmt\While_ || $stmt instanceof Stmt\Do_ || $stmt instanceof Stmt\For_ || $stmt instanceof Stmt\Foreach_; + if ( $innermost && ! $is_loop ) { + return false; + } + return $this->writes_variable( $stmt, $name, false ); + } + /** * Determines whether a node may write to a variable. * From a50bd581c5351315b64fb7abbce1a9b9819eb519 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:10:51 -0800 Subject: [PATCH 10/21] Code Quality: Do not follow arrow function parameters for wpdb queries. An arrow function has no statements of its own, so `WpdbQueryVisitor` follows the variables in it to the statements outside it, as it should for the variables the arrow function captures. But its parameters shadow the variables outside it of the same name, so for `fn( $sql ) => $wpdb->get_var( $sql )` the visitor typed the result from an assignment to `$sql` outside, rather than from the argument. The parameters of the arrow functions a call is in are now unknown. The variables outside are still followed for the rest. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- tests/phpstan/WpdbQueryVisitor.php | 34 +++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/tests/phpstan/WpdbQueryVisitor.php b/tests/phpstan/WpdbQueryVisitor.php index ec14387dc8d1e..68a7f931a451c 100644 --- a/tests/phpstan/WpdbQueryVisitor.php +++ b/tests/phpstan/WpdbQueryVisitor.php @@ -13,6 +13,7 @@ use PhpParser\Node; use PhpParser\Node\Arg; use PhpParser\Node\Expr; +use PhpParser\Node\Expr\ArrowFunction; use PhpParser\Node\Expr\Assign; use PhpParser\Node\Expr\AssignOp; use PhpParser\Node\Expr\AssignRef; @@ -99,6 +100,13 @@ final class WpdbQueryVisitor extends NodeVisitorAbstract { */ private NodeFinder $node_finder; + /** + * Names of the parameters of the arrow functions being walked, which shadow the variables outside them. + * + * @var array + */ + private array $shadowed = array(); + /** * Constructor. */ @@ -143,6 +151,23 @@ private function walk_statements( array $stmts, array $frames ): void { * @param list, 1: int }> $position Position of the statement the node is in. */ private function walk_node( Node $node, array $position ): void { + $shadowed = $this->shadowed; + if ( $node instanceof FunctionLike ) { + /* + * An arrow function has no statements of its own, so the variables in it are followed outside it, except + * its parameters. Another function starts a new scope, whose variables are followed in it alone. + */ + if ( $node instanceof ArrowFunction ) { + foreach ( $node->getParams() as $param ) { + if ( $param->var instanceof Variable && is_string( $param->var->name ) ) { + $this->shadowed[ $param->var->name ] = true; + } + } + } else { + $this->shadowed = array(); + } + } + foreach ( $node->getSubNodeNames() as $name ) { $sub_node = $node->$name; if ( is_array( $sub_node ) ) { @@ -161,6 +186,7 @@ private function walk_node( Node $node, array $position ): void { $this->walk_node( $sub_node, $position ); } } + $this->shadowed = $shadowed; if ( $node instanceof MethodCall @@ -221,7 +247,13 @@ private function evaluate( Expr $expr, array $position, int $depth ): string { ); } - if ( $expr instanceof Variable && is_string( $expr->name ) && $depth < self::MAX_DEPTH ) { + if ( + $expr instanceof Variable + && is_string( $expr->name ) + && $depth < self::MAX_DEPTH + // A parameter of an arrow function the call is in, whose value is not assigned by a statement. + && ! ( 0 === $depth && isset( $this->shadowed[ $expr->name ] ) ) + ) { return $this->resolve_variable( $expr->name, $position, $depth + 1 ); } From 36cdd236b09dd681722211047b026013a6fc5130 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:12:01 -0800 Subject: [PATCH 11/21] Code Quality: Name more unaliased select expressions as MySQL does. `WpdbSelectParser` took the name at the end of a select expression as its alias whenever a name, literal, or `)` came before it. But a keyword ends some expressions, which so read as their alias: * the unit of an interval, as in `post_date + INTERVAL 1 DAY`, and * the operand of a keyword like `COLLATE` or `BINARY`, as in `post_title COLLATE utf8mb4_bin`, or as in `BINARY post_name`, which then also read as a reference to the `post_name` column. A name following such a keyword, and the unit of an interval outside any parentheses, is no longer taken as an alias, so the expression is named by its text. A string literal without an alias was also named by its text, quotes and all, but MySQL names it by its value, or by the first of adjacent strings it joins, as it now is here. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- tests/phpstan/WpdbSelectParser.php | 40 ++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/tests/phpstan/WpdbSelectParser.php b/tests/phpstan/WpdbSelectParser.php index efae3ef7c2b72..f012ef09ad3de 100644 --- a/tests/phpstan/WpdbSelectParser.php +++ b/tests/phpstan/WpdbSelectParser.php @@ -65,6 +65,16 @@ final class WpdbSelectParser { */ private const NON_ALIAS_KEYWORDS = array( 'END', 'NULL', 'TRUE', 'FALSE', 'ASC', 'DESC', 'DISTINCT' ); + /** + * Keywords which an operand follows, so that a name following one is not an alias. + */ + private const OPERAND_KEYWORDS = array( 'AND', 'BETWEEN', 'BINARY', 'CASE', 'COLLATE', 'DIV', 'ELSE', 'ESCAPE', 'IN', 'INTERVAL', 'IS', 'LIKE', 'MOD', 'NOT', 'OR', 'REGEXP', 'RLIKE', 'THEN', 'WHEN', 'XOR' ); + + /** + * Units of an `INTERVAL`, as in `post_date + INTERVAL 1 DAY`, which are not an alias there. + */ + private const INTERVAL_UNITS = array( 'MICROSECOND', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'WEEK', 'MONTH', 'QUARTER', 'YEAR', 'SECOND_MICROSECOND', 'MINUTE_MICROSECOND', 'MINUTE_SECOND', 'HOUR_MICROSECOND', 'HOUR_SECOND', 'HOUR_MINUTE', 'DAY_MICROSECOND', 'DAY_SECOND', 'DAY_MINUTE', 'DAY_HOUR', 'YEAR_MONTH' ); + /** * Schema of the core tables. * @@ -324,6 +334,8 @@ private function get_item_columns( array $item, array $tables, string $query ): $item = array_slice( $item, 0, $count - 2 ); } elseif ( $count >= 2 + && ! in_array( strtoupper( $previous ), self::OPERAND_KEYWORDS, true ) + && ! ( in_array( strtoupper( $last_text ), self::INTERVAL_UNITS, true ) && self::has_top_level_token( $item, 'INTERVAL' ) ) && ( // A string following a string literal is not an alias, but is joined to it. ( self::is_quoted_string( $last_text ) && ( ')' === $previous || self::is_identifier( $previous ) ) ) @@ -373,8 +385,13 @@ private function get_item_columns( array $item, array $tables, string $query ): ); } - // Otherwise MySQL names the column by the text of its expression. - if ( null === $alias ) { + /* + * Otherwise MySQL names the column by the value of a string, or the first of adjacent strings it joins, or else + * by the text of its expression. + */ + if ( null === $alias && array() === array_filter( $texts, static fn ( string $text ): bool => ! self::is_quoted_string( $text ) ) ) { + $alias = self::unquote( $texts[0] ); + } elseif ( null === $alias ) { $last = end( $item ); $text = (string) substr( $query, $item[0]['offset'], $last['offset'] + strlen( $last['text'] ) - $item[0]['offset'] ); $alias = false === strpos( $text, '{' ) ? $text : null; @@ -594,6 +611,25 @@ private static function is_keyword_value( string $text ): bool { return in_array( strtoupper( $text ), array( 'NULL', 'TRUE', 'FALSE', 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_USER' ), true ); } + /** + * Determines whether an expression has a keyword outside any parentheses. + * + * @param list $item Tokens of the expression. + * @param string $keyword Uppercase keyword. + * @return bool + * @phpstan-param list $item + */ + private static function has_top_level_token( array $item, string $keyword ): bool { + $depth = 0; + foreach ( $item as $token ) { + if ( 0 === $depth && strtoupper( $token['text'] ) === $keyword ) { + return true; + } + $depth += self::get_depth_change( $token['text'] ); + } + return false; + } + /** * Determines whether a token is a quoted string, with single or double quotes. * From 6f529d8d6d611088c3de96685f362f3d5948bf02 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:12:16 -0800 Subject: [PATCH 12/21] Code Quality: Put a `return` in the wpdb query type extension on its own line. Two statements shared a line, joined by a run of tabs. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php index e8c4ee0a56252..fef2146300c3a 100644 --- a/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php +++ b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php @@ -167,7 +167,8 @@ public function getTypeFromMethodCall( MethodReflection $methodReflection, Metho default: $declared = ParametersAcceptorSelector::selectFromArgs( $scope, $args, $methodReflection->getVariants() )->getReturnType(); - $refined = $this->refine_rows( $declared, $columns, $result['complete'] ); return $refined->equals( $declared ) ? null : $refined; + $refined = $this->refine_rows( $declared, $columns, $result['complete'] ); + return $refined->equals( $declared ) ? null : $refined; } } From 86629821d25af21ce1e526bb07277efde6cdf7cb Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:13:03 -0800 Subject: [PATCH 13/21] Docs: Add serial commas to the wpdb query type documentation. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- tests/phpstan/README.md | 4 ++-- tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php | 2 +- tests/phpstan/WpdbQueryVisitor.php | 4 ++-- tests/phpstan/base.neon | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/phpstan/README.md b/tests/phpstan/README.md index 541393c0f55f7..1343ca0c56385 100644 --- a/tests/phpstan/README.md +++ b/tests/phpstan/README.md @@ -211,7 +211,7 @@ These identifiers are specific to WordPress, and can be ignored or baselined lik ### Database query results -`WpdbQueryDynamicMethodReturnTypeExtension` types the results of `$wpdb->get_var()`, `get_row()`, `get_col()` and `get_results()` from the columns their query selects, so that they need no inline `@var` tag. For example: +`WpdbQueryDynamicMethodReturnTypeExtension` types the results of `$wpdb->get_var()`, `get_row()`, `get_col()`, and `get_results()` from the columns their query selects, so that they need no inline `@var` tag. For example: ```php $post = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_title FROM $wpdb->posts WHERE ID = %d", $id ) ); @@ -221,7 +221,7 @@ is typed `(object{ID: decimal-int-string, post_title: string}&stdClass)|null` ra - **The columns of core tables are typed from the schema.** They are read from the `CREATE TABLE` statements in `wp_get_db_schema()`, so a column added there needs no change here. `wpdb` returns every value as a string, or null for SQL `NULL`, so an integer column is a `decimal-int-string`, a `DATETIME` column a `non-falsy-string`, and a column without `NOT NULL` is nullable. The `spam` and `deleted` columns, which `users` only has on multisite, are optional. - **Select expressions are named and typed as MySQL does.** An alias names a column, as does the text of an expression without one, like `COUNT(*)`. `COUNT()` is a `decimal-int-string`, `SUM()` and `AVG()` are a nullable `numeric-string`, `MIN()` and `MAX()` of a column are the column's type or null, and a literal is that constant string. Anything else, including a column of a table that is not a core table, is `string|null`, which is what any value can be. -- **A query built up in variables is followed.** The query is reconstructed from the syntax tree, by `WpdbQueryVisitor`: literals, interpolation, `$wpdb->prepare()` and concatenation are joined, `$wpdb->posts` and the like name the table, and a variable is replaced by what the statements before the call assign and append to it. Only what the select list and the `FROM` clause need must be known, so a `WHERE` clause built from parameters does no harm. The variable is not followed through a loop which writes to it, or through a branch which does more than append to it. +- **A query built up in variables is followed.** The query is reconstructed from the syntax tree, by `WpdbQueryVisitor`: literals, interpolation, `$wpdb->prepare()`, and concatenation are joined, `$wpdb->posts` and the like name the table, and a variable is replaced by what the statements before the call assign and append to it. Only what the select list and the `FROM` clause need must be known, so a `WHERE` clause built from parameters does no harm. The variable is not followed through a loop which writes to it, or through a branch which does more than append to it. Where the columns cannot be determined, such as for `SELECT *` from a table that is not a core table, for a select list holding a variable, or for a query that is not `SELECT`, the method's declared return type is used as before. The cases in which a method returns null or an empty array are as declared either way, since they depend on its arguments rather than the query. diff --git a/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php index fef2146300c3a..30867150f0e77 100644 --- a/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php +++ b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php @@ -33,7 +33,7 @@ use PHPStan\Type\TypeTraverser; /** - * Types the results of `wpdb::get_var()`, `get_row()`, `get_col()` and + * Types the results of `wpdb::get_var()`, `get_row()`, `get_col()`, and * `get_results()` from the columns their query selects. * * For example, given: diff --git a/tests/phpstan/WpdbQueryVisitor.php b/tests/phpstan/WpdbQueryVisitor.php index 68a7f931a451c..a5fe4f87c257a 100644 --- a/tests/phpstan/WpdbQueryVisitor.php +++ b/tests/phpstan/WpdbQueryVisitor.php @@ -32,7 +32,7 @@ /** * Attaches the text of the SQL query passed to `wpdb::get_var()`, `get_row()`, - * `get_col()` and `get_results()` to the method call node. + * `get_col()`, and `get_results()` to the method call node. * * The type of a query is rarely a constant string, since it almost always * interpolates a table name like `$wpdb->posts`, so the query text cannot be @@ -40,7 +40,7 @@ * call, which a type extension cannot see the statements of. So this visitor * reconstructs the text from the syntax tree instead, before analysis: * - * - String literals, interpolation and concatenation are joined. + * - String literals, interpolation, and concatenation are joined. * - A table property on `$wpdb`, like `$wpdb->posts`, becomes the placeholder * `{wpdb:posts}`, so that the query parser knows which table it names. * - `$wpdb->prepare( $query, ... )` is replaced by its query, with the diff --git a/tests/phpstan/base.neon b/tests/phpstan/base.neon index 1cd68fc324b6a..8a246f8a12590 100644 --- a/tests/phpstan/base.neon +++ b/tests/phpstan/base.neon @@ -52,7 +52,7 @@ services: tags: - phpstan.parser.richParserNodeVisitor - # Types the results of wpdb::get_var(), get_row(), get_col() and get_results() + # Types the results of wpdb::get_var(), get_row(), get_col(), and get_results() # from the columns their query selects, typed from the core database schema. - class: WordPress\PHPStan\WpdbQueryDynamicMethodReturnTypeExtension From c5bcef213f14d3d3fd007f1f1a2356f86386cfe2 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:17:13 -0800 Subject: [PATCH 14/21] Docs: Document the recent refinements to the wpdb query types. Describe in the README how the extension now types outer-joined columns, `ARRAY_N` rows with the multisite columns, quoted aliases, string literals, repeated column names, and `prepare()` placeholders, and when it no longer follows a variable: past an `if` condition assigning it, and for an arrow function's parameter. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- tests/phpstan/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/phpstan/README.md b/tests/phpstan/README.md index 1343ca0c56385..c4e9f9ec1fc68 100644 --- a/tests/phpstan/README.md +++ b/tests/phpstan/README.md @@ -219,9 +219,9 @@ $post = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_title FROM $wpdb->posts is typed `(object{ID: decimal-int-string, post_title: string}&stdClass)|null` rather than `stdClass|null`. Likewise, `ARRAY_A` and `ARRAY_N` rows become array shapes, `OBJECT_K` results are keyed by the first column's type, and `get_var()` and `get_col()` give the type of the column they return. -- **The columns of core tables are typed from the schema.** They are read from the `CREATE TABLE` statements in `wp_get_db_schema()`, so a column added there needs no change here. `wpdb` returns every value as a string, or null for SQL `NULL`, so an integer column is a `decimal-int-string`, a `DATETIME` column a `non-falsy-string`, and a column without `NOT NULL` is nullable. The `spam` and `deleted` columns, which `users` only has on multisite, are optional. -- **Select expressions are named and typed as MySQL does.** An alias names a column, as does the text of an expression without one, like `COUNT(*)`. `COUNT()` is a `decimal-int-string`, `SUM()` and `AVG()` are a nullable `numeric-string`, `MIN()` and `MAX()` of a column are the column's type or null, and a literal is that constant string. Anything else, including a column of a table that is not a core table, is `string|null`, which is what any value can be. -- **A query built up in variables is followed.** The query is reconstructed from the syntax tree, by `WpdbQueryVisitor`: literals, interpolation, `$wpdb->prepare()`, and concatenation are joined, `$wpdb->posts` and the like name the table, and a variable is replaced by what the statements before the call assign and append to it. Only what the select list and the `FROM` clause need must be known, so a `WHERE` clause built from parameters does no harm. The variable is not followed through a loop which writes to it, or through a branch which does more than append to it. +- **The columns of core tables are typed from the schema.** They are read from the `CREATE TABLE` statements in `wp_get_db_schema()`, so a column added there needs no change here. `wpdb` returns every value as a string, or null for SQL `NULL`, so an integer column is a `decimal-int-string`, a `DATETIME` column a `non-falsy-string`, and a column without `NOT NULL` is nullable. So is each column of a table on the outer side of a `LEFT JOIN` or `RIGHT JOIN`, which has no row to match for some rows of the result. The `spam` and `deleted` columns, which `users` only has on multisite, are optional, and an `ARRAY_N` row is typed both with and without them, since they shift the positions of the columns after them. +- **Select expressions are named and typed as MySQL does.** An alias names a column, whether a name or a quoted string, as does the text of an expression without one, like `COUNT(*)`, or the value of a string literal. Where columns share a name, the last one's value is the one in the row. `COUNT()` is a `decimal-int-string`, `SUM()` and `AVG()` are a nullable `numeric-string`, `MIN()` and `MAX()` of a column are the column's type or null, and a literal is that constant string. Anything else, including a column of a table that is not a core table, is `string|null`, which is what any value can be. +- **A query built up in variables is followed.** The query is reconstructed from the syntax tree, by `WpdbQueryVisitor`: literals, interpolation, `$wpdb->prepare()`, and concatenation are joined, each placeholder of a prepared query is a single unknown value, `$wpdb->posts` and the like name the table, and a variable is replaced by what the statements before the call assign and append to it. Only what the select list and the `FROM` clause need must be known, so a `WHERE` clause built from parameters does no harm. The variable is not followed through a loop which writes to it, through a branch which does more than append to it, or past an `if` condition which assigns it, and an arrow function's parameter is not followed outside it. Where the columns cannot be determined, such as for `SELECT *` from a table that is not a core table, for a select list holding a variable, or for a query that is not `SELECT`, the method's declared return type is used as before. The cases in which a method returns null or an empty array are as declared either way, since they depend on its arguments rather than the query. From af3f69d709398f203997836f68e38908a1a6e221 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:30:25 -0800 Subject: [PATCH 15/21] Code Quality: Leave wpdb row types as declared for a non-constant `$output`. When the `$output` argument of `get_row()` or `get_results()` may be more than one value, as for `'ARRAY_A'|'ARRAY_N'` or any `string`, the declared conditional return type joins the row arrays of the two into one `array`. The extension then refined that as an `ARRAY_A` row alone, so an `ARRAY_N` row, which the call may well return, was left out of the type. The result is now left as declared unless `$output` is absent or one constant value. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- .../phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php index 30867150f0e77..2f5d441e4687f 100644 --- a/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php +++ b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php @@ -166,6 +166,14 @@ public function getTypeFromMethodCall( MethodReflection $methodReflection, Metho return null !== $value ? TypeCombinator::intersect( new ArrayType( new IntegerType(), $value ), new AccessoryArrayListType() ) : null; default: + /* + * For an `$output` of more than one value, the declared conditional return type joins the row arrays of + * `ARRAY_A` and `ARRAY_N` into one `array`, which could then only be refined as one or the other. + */ + if ( isset( $args[1] ) && 1 !== count( $scope->getType( $args[1]->value )->getConstantStrings() ) ) { + return null; + } + $declared = ParametersAcceptorSelector::selectFromArgs( $scope, $args, $methodReflection->getVariants() )->getReturnType(); $refined = $this->refine_rows( $declared, $columns, $result['complete'] ); return $refined->equals( $declared ) ? null : $refined; From f3b773e854a16a6091ba0a04189b3d1470709798 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:31:45 -0800 Subject: [PATCH 16/21] Code Quality: Leave column names holding unknown text unknown in wpdb query types. `WpdbSelectParser` left a column's name unknown when it was the text of an expression with a placeholder in it, but not otherwise. So a placeholder inside a backtick-quoted name or a string, as in ``SELECT `$column` `` or `SELECT '%s'`, or a `wpdb` property other than a table, as in `SELECT $wpdb->blogid`, became a column named `{?}`, `{value}`, or `{wpdb:blogid}`. The real column has another name, and two such columns shared the one name, so were taken as a single value of the row. Any column name holding a placeholder is now unknown, whether it comes from an alias, a column reference, a string, or the text of an expression. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- tests/phpstan/WpdbSelectParser.php | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/tests/phpstan/WpdbSelectParser.php b/tests/phpstan/WpdbSelectParser.php index f012ef09ad3de..480c9b3e0bb06 100644 --- a/tests/phpstan/WpdbSelectParser.php +++ b/tests/phpstan/WpdbSelectParser.php @@ -30,7 +30,8 @@ * - Anything else is `string|null`, which is every value `wpdb` can return. * * A column's name is its alias, or else its name for a column reference, or - * else the text of its expression, as MySQL names them. + * else the text of its expression, as MySQL names them. A name holding a part + * whose text is not known is itself unknown. * * The columns are incomplete from the first one whose count is not known: a * `*` over a table that is not a core table, or a select expression with an @@ -378,7 +379,7 @@ private function get_item_columns( array $item, array $tables, string $query ): $column = $this->find_column( $tables, $qualifier, $name ); return array( array( - 'name' => $alias ?? $name, + 'name' => self::get_known_name( $alias ?? $name ), 'type' => null !== $column ? $column['type'] : 'string|null', 'optional' => null !== $column && $column['optional'], ), @@ -393,13 +394,12 @@ private function get_item_columns( array $item, array $tables, string $query ): $alias = self::unquote( $texts[0] ); } elseif ( null === $alias ) { $last = end( $item ); - $text = (string) substr( $query, $item[0]['offset'], $last['offset'] + strlen( $last['text'] ) - $item[0]['offset'] ); - $alias = false === strpos( $text, '{' ) ? $text : null; + $alias = (string) substr( $query, $item[0]['offset'], $last['offset'] + strlen( $last['text'] ) - $item[0]['offset'] ); } return array( array( - 'name' => $alias, + 'name' => self::get_known_name( $alias ), 'type' => $this->get_expression_type( $texts, $tables ), 'optional' => false, ), @@ -611,6 +611,19 @@ private static function is_keyword_value( string $text ): bool { return in_array( strtoupper( $text ), array( 'NULL', 'TRUE', 'FALSE', 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_USER' ), true ); } + /** + * Gets a column name, unless it holds a placeholder, whose text is not known. + * + * A placeholder can be in a name as well as be one, as in `` `{?}` `` or `'{value}'`, or a `wpdb` property + * other than a table, like `{wpdb:blogid}`. + * + * @param string|null $name Column name. + * @return string|null Column name, or null if unknown. + */ + private static function get_known_name( ?string $name ): ?string { + return null !== $name && false === strpos( $name, '{' ) ? $name : null; + } + /** * Determines whether an expression has a keyword outside any parentheses. * From ce7d48e3fb79acc788a840697a3362f7c24d7669 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:32:43 -0800 Subject: [PATCH 17/21] Code Quality: Follow writes in the statement of a wpdb query call. `WpdbQueryVisitor` did not check the statement a query method call is in for writes to the query's variable, unless it was a loop or an `if`, so it missed a write made earlier in the same statement, as in `( $sql = get_option( 'query' ) ) && $wpdb->get_var( $sql )`, and typed the result from the value assigned before it. A write to the variable anywhere in that statement now makes its value unknown, since the visitor does not follow the order in which the parts of a statement run. An assignment to the variable of a value holding the call, as in `$sql = $wpdb->get_var( $sql )`, is the exception, as its write is made after the call. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- tests/phpstan/WpdbQueryVisitor.php | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/tests/phpstan/WpdbQueryVisitor.php b/tests/phpstan/WpdbQueryVisitor.php index a5fe4f87c257a..a8a34060f0cf7 100644 --- a/tests/phpstan/WpdbQueryVisitor.php +++ b/tests/phpstan/WpdbQueryVisitor.php @@ -320,8 +320,10 @@ private function resolve_variable( string $name, array $position, int $depth ): * and so on. The exception is an `if`: of its branches, only the one the position is in has run, after the * conditions. * - * The innermost statement is the one the position is in directly, which runs before the position only where it is - * a loop, whose body may have run in an earlier iteration, or the conditions of an `if`. + * The innermost statement is the one the position is in directly. Any write to the variable in it is taken to + * have run before the position, since the order in which the parts of a statement run is not followed here, and a + * loop's body may have run in an earlier iteration. The exceptions are the branches of an `if`, which run after + * its conditions, and an assignment to the variable, which is made after the value being assigned. * * @param Node $stmt Statement. * @param string $name Variable name. @@ -343,8 +345,15 @@ private function may_write_before( Node $stmt, string $name, bool $innermost ): } $is_loop = $stmt instanceof Stmt\While_ || $stmt instanceof Stmt\Do_ || $stmt instanceof Stmt\For_ || $stmt instanceof Stmt\Foreach_; - if ( $innermost && ! $is_loop ) { - return false; + if ( + $innermost + && ! $is_loop + && $stmt instanceof Stmt\Expression + && ( $stmt->expr instanceof Assign || $stmt->expr instanceof AssignOp ) + && $this->is_variable( $stmt->expr->var, $name ) + ) { + // An assignment to the variable is made after its value, which the position is in, is evaluated. + return $this->writes_variable( $stmt->expr->expr, $name, false ); } return $this->writes_variable( $stmt, $name, false ); } From 7b51cf7be0c8f82b7863f368a721cb7f06103721 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:33:43 -0800 Subject: [PATCH 18/21] Code Quality: Type `OBJECT_K` keys from the first value of the row. `wpdb::get_results()` keys `OBJECT_K` rows by the first value of each row object, not by its first select column. The two differ when a later column has the first column's name, as in `SELECT ID, post_title AS ID`, whose value then replaces the first, and so whose type the keys have. The key is now typed from the first value of the row, as the positional types are, in each variant of the row. This also types the keys when the first column is one of the multisite columns of the users table, which were left as declared. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- ...dbQueryDynamicMethodReturnTypeExtension.php | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php index 2f5d441e4687f..40acd271c3566 100644 --- a/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php +++ b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php @@ -323,15 +323,23 @@ private function refine_rows( Type $declared, array $columns, bool $complete ): $list_row = TypeCombinator::union( ...$list_rows ); } - // `OBJECT_K` keys the rows by the first column's value, with null as ''. - $key = null; - if ( isset( $columns[0] ) && ! $columns[0]['optional'] ) { - $key = $columns[0]['type']; + /* + * `OBJECT_K` keys the rows by the first value of the row object, with null as ''. That is the value of the + * last column with the first column's name, and on some sites, of another column if the first is not there. + */ + $keys = array(); + foreach ( self::get_row_variants( $columns ) as $variant ) { + if ( ! isset( $variant[0] ) ) { + $keys = array(); + break; + } + $key = $variant[0]; if ( ! $key->isNull()->no() ) { $key = TypeCombinator::union( TypeCombinator::removeNull( $key ), new ConstantStringType( '' ) ); } - $key = $key->toArrayKey(); + $keys[] = $key->toArrayKey(); } + $key = array() !== $keys ? TypeCombinator::union( ...$keys ) : null; return self::replace_rows( $declared, From ec7b55631bc43d478f5a20a828a45b96cff6067a Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:34:56 -0800 Subject: [PATCH 19/21] Code Quality: Do not take a table name extended by more text as the core table. `WpdbSelectParser` split a table placeholder from the name characters next to it, so `{$wpdb->posts}_archive` read as the posts table with the alias `_archive`, and its columns were typed from the posts schema, though it is another table. A table placeholder with name characters on either side is now one token with them, which is not a core table. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- tests/phpstan/WpdbSelectParser.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/phpstan/WpdbSelectParser.php b/tests/phpstan/WpdbSelectParser.php index 480c9b3e0bb06..2732aed7ecf64 100644 --- a/tests/phpstan/WpdbSelectParser.php +++ b/tests/phpstan/WpdbSelectParser.php @@ -537,13 +537,16 @@ private static function get_column_reference( array $texts ): ?array { /** * Splits a query into tokens, leaving out whitespace and comments. * + * A table placeholder with name characters on either side of it, as in `{wpdb:posts}_archive`, is one token with + * them, since together they name some other table. + * * @param string $query Query. * @return list * @phpstan-return list */ private static function tokenize( string $query ): array { preg_match_all( - '/\s+|--[^\n]*|\/\*.*?\*\/|\'(?:[^\'\\\\]|\\\\.|\'\')*\'|"(?:[^"\\\\]|\\\\.|"")*"|`[^`]*`|\{[^{}]*\}|\d+(?:\.\d+)?|[\w$]+|<=>|[<>!]=|<>|\|\||&&|./s', + '/\s+|--[^\n]*|\/\*.*?\*\/|\'(?:[^\'\\\\]|\\\\.|\'\')*\'|"(?:[^"\\\\]|\\\\.|"")*"|`[^`]*`|[\w$]*\{wpdb:\w+\}[\w$]*|\{[^{}]*\}|\d+(?:\.\d+)?|[\w$]+|<=>|[<>!]=|<>|\|\||&&|./s', $query, $matches, PREG_OFFSET_CAPTURE From 21d024b28ad169f526898c1e01cb0c70332ee1cb Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:35:40 -0800 Subject: [PATCH 20/21] Code Quality: Include null in `get_col()` types for any column index. For a column index which may be any integer, the extension typed the values of `get_col()` from the types of the columns alone. But an index past the last column gives a value of null in every row, as `get_var()` does for it, so null is now included in their type too. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php index 40acd271c3566..42ad8732a6cae 100644 --- a/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php +++ b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php @@ -194,6 +194,7 @@ public function getTypeFromMethodCall( MethodReflection $methodReflection, Metho private function get_positional_value_type( array $columns, bool $complete, ?\PhpParser\Node\Expr $x, Scope $scope ): ?Type { $variants = self::get_row_variants( $columns ); + $types = array(); $indexes = array( 0 ); if ( null !== $x ) { $indexes = array(); @@ -209,10 +210,11 @@ private function get_positional_value_type( array $columns, bool $complete, ?\Ph return null; } $indexes = array_keys( $variants[0] ); + // Or an index past the last column, for which the value is null. + $types[] = new NullType(); } } - $types = array(); foreach ( $indexes as $index ) { foreach ( $variants as $variant ) { if ( ! isset( $variant[ $index ] ) ) { From ad1b63dba0f21b559895a79ee8fd8c3ebdfb7ffa Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 26 Nov 2026 00:37:38 -0800 Subject: [PATCH 21/21] Code Quality: Read number and prefixed string literals whole in wpdb query types. `WpdbSelectParser` read the digits at the start of a number as the number, and the rest as an alias, so `SELECT 0x41` was typed as the constant `'0'` in a column named `x41`, and `SELECT 1e3` as `'1'` in a column named `e3`. And it typed any run of digits as the same constant string, though MySQL gives back `007` as `'7'`. Likewise a string with a prefix, like `x'41'` or `_utf8mb4'text'`, read as a column reference with the string as its alias. Hexadecimal numbers, decimal numbers with an exponent, and strings with a prefix are now each one token. Only an integer written as MySQL gives it back is typed as a constant string, and the name of a prefixed string, which this does not follow, is left unknown. Co-Authored-By: Claude Opus 5.5 (medium effort) Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c --- tests/phpstan/WpdbSelectParser.php | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/tests/phpstan/WpdbSelectParser.php b/tests/phpstan/WpdbSelectParser.php index 2732aed7ecf64..821ce8c3c1b18 100644 --- a/tests/phpstan/WpdbSelectParser.php +++ b/tests/phpstan/WpdbSelectParser.php @@ -388,18 +388,19 @@ private function get_item_columns( array $item, array $tables, string $query ): /* * Otherwise MySQL names the column by the value of a string, or the first of adjacent strings it joins, or else - * by the text of its expression. + * by the text of its expression. The name of a string with a prefix, like `_utf8mb4'text'`, is not followed. */ - if ( null === $alias && array() === array_filter( $texts, static fn ( string $text ): bool => ! self::is_quoted_string( $text ) ) ) { - $alias = self::unquote( $texts[0] ); - } elseif ( null === $alias ) { - $last = end( $item ); - $alias = (string) substr( $query, $item[0]['offset'], $last['offset'] + strlen( $last['text'] ) - $item[0]['offset'] ); + $name = $alias; + if ( null === $name && array() === array_filter( $texts, static fn ( string $text ): bool => ! self::is_quoted_string( $text ) ) ) { + $name = self::unquote( $texts[0] ); + } elseif ( null === $name && ! ( 1 === $count && preg_match( '/^(?:[xXbBnN]|_[A-Za-z0-9]+)\'/', $texts[0] ) ) ) { + $last = end( $item ); + $name = (string) substr( $query, $item[0]['offset'], $last['offset'] + strlen( $last['text'] ) - $item[0]['offset'] ); } return array( array( - 'name' => self::get_known_name( $alias ), + 'name' => self::get_known_name( $name ), 'type' => $this->get_expression_type( $texts, $tables ), 'optional' => false, ), @@ -417,7 +418,8 @@ private function get_item_columns( array $item, array $tables, string $query ): private function get_expression_type( array $texts, array $tables ): string { $count = count( $texts ); - if ( 1 === $count && preg_match( '/^-?\d+$/', $texts[0] ) ) { + // An integer, written as MySQL gives it back. Others, like `007` or `1e3`, are given back otherwise. + if ( 1 === $count && preg_match( '/^(?:0|[1-9]\d*)$/', $texts[0] ) ) { return "'" . $texts[0] . "'"; } if ( 1 === $count && preg_match( "/^'([\\w .:-]*)'$/", $texts[0], $match ) ) { @@ -540,13 +542,16 @@ private static function get_column_reference( array $texts ): ?array { * A table placeholder with name characters on either side of it, as in `{wpdb:posts}_archive`, is one token with * them, since together they name some other table. * + * A literal is one token, including a number like `0x41` or `1e3`, and a string with a prefix, like `x'41'` or + * `_utf8mb4'text'`. A name may start with digits, as in `1st`, but not be all digits. + * * @param string $query Query. * @return list * @phpstan-return list */ private static function tokenize( string $query ): array { preg_match_all( - '/\s+|--[^\n]*|\/\*.*?\*\/|\'(?:[^\'\\\\]|\\\\.|\'\')*\'|"(?:[^"\\\\]|\\\\.|"")*"|`[^`]*`|[\w$]*\{wpdb:\w+\}[\w$]*|\{[^{}]*\}|\d+(?:\.\d+)?|[\w$]+|<=>|[<>!]=|<>|\|\||&&|./s', + '/\s+|--[^\n]*|\/\*.*?\*\/|\'(?:[^\'\\\\]|\\\\.|\'\')*\'|"(?:[^"\\\\]|\\\\.|"")*"|`[^`]*`|[\w$]*\{wpdb:\w+\}[\w$]*|\{[^{}]*\}|(?:[xXbBnN]|_[A-Za-z0-9]+)\'(?:[^\'\\\\]|\\\\.|\'\')*\'|0x[0-9a-fA-F]+(?![\w$])|\d+(?:\.\d+)?(?:[eE][-+]?\d+)?(?![\w$])|[\w$]+|<=>|[<>!]=|<>|\|\||&&|./s', $query, $matches, PREG_OFFSET_CAPTURE @@ -601,7 +606,7 @@ private static function is_identifier( string $text ): bool { * @return bool */ private static function is_literal( string $text ): bool { - return WpdbQueryVisitor::VALUE === $text || (bool) preg_match( '/^(?:\d|\'|")/', $text ); + return WpdbQueryVisitor::VALUE === $text || (bool) preg_match( '/^(?:\d|\'|"|(?:[xXbBnN]|_[A-Za-z0-9]+)\')/', $text ); } /**