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..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,16 +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"; - /** @var list|null $counts */ + $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 ); - /** @var list|null $user_rows */ + $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 ) { 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 ) ) { diff --git a/tests/phpstan/README.md b/tests/phpstan/README.md index 520f8c76ebdb5..c4e9f9ec1fc68 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. 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. + +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..42ad8732a6cae --- /dev/null +++ b/tests/phpstan/WpdbQueryDynamicMethodReturnTypeExtension.php @@ -0,0 +1,451 @@ +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: + /* + * 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; + } + } + + /** + * 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 { + $variants = self::get_row_variants( $columns ); + + $types = array(); + $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 ( ! $complete ) { + return null; + } + $indexes = array_keys( $variants[0] ); + // Or an index past the last column, for which the value is null. + $types[] = new NullType(); + } + } + + foreach ( $indexes as $index ) { + 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; + } + $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(); + } + } + } + + return TypeCombinator::union( ...$types ); + } + + /** + * 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, 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. + * + * 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 = 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 ) { + $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']; + } + // Replacing a value at its position keeps the keys sequential. + return array_values( $values ); + } + + /** + * 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 ) { + $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 = TypeCombinator::union( ...$list_rows ); + } + + /* + * `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( '' ) ); + } + $keys[] = $key->toArrayKey(); + } + $key = array() !== $keys ? TypeCombinator::union( ...$keys ) : null; + + 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..a8a34060f0cf7 --- /dev/null +++ b/tests/phpstan/WpdbQueryVisitor.php @@ -0,0 +1,432 @@ +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, 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 + * 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 = '{?}'; + + /** + * 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. + */ + 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; + + /** + * Names of the parameters of the arrow functions being walked, which shadow the variables outside them. + * + * @var array + */ + private array $shadowed = array(); + + /** + * 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 { + $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 ) ) { + 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 ); + } + } + $this->shadowed = $shadowed; + + 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 + ) { + // 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 + // 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 ); + } + + 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 ]; + + if ( $this->may_write_before( $stmts[ $index ], $name, count( $position ) - 1 === $level ) ) { + 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 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. 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. + * @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 + && $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 ); + } + + /** + * 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..821ce8c3c1b18 --- /dev/null +++ b/tests/phpstan/WpdbSelectParser.php @@ -0,0 +1,680 @@ +}`, an unknown part is `{?}`, and an unknown + * single value, from a placeholder, is `{value}`. + * + * 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, 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. + * - 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. 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 + * 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-type Table array{ name: string|null, nullable: bool } + * @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' ); + + /** + * 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. + * + * @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 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 ); + + // 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; + $outer_join = null; + $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; + } + + // `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; + } + + 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; + } + + // 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; + } + + $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-param array $tables + * @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, 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 + && ! 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 ) ) ) + || ( + 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( $last_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 || null === $table['name'] ) { + return null; + } + foreach ( $this->schema->get_columns( $table['name'] ) as $column ) { + $columns[] = self::apply_nullable( $column, $table ); + } + } + 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' => self::get_known_name( $alias ?? $name ), + 'type' => null !== $column ? $column['type'] : 'string|null', + 'optional' => null !== $column && $column['optional'], + ), + ); + } + + /* + * 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. The name of a string with a prefix, like `_utf8mb4'text'`, is not followed. + */ + $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( $name ), + '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. + * @phpstan-param array $tables + */ + private function get_expression_type( array $texts, array $tables ): string { + $count = count( $texts ); + + // 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 ) ) { + 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 self::add_null( $column['type'] ); + } + 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-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; + 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['name'] ? $this->schema->get_column( $table['name'], $name ) : null; + if ( null !== $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`. + * + * @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. + * + * 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$]*|\{[^{}]*\}|(?:[xXbBnN]|_[A-Za-z0-9]+)\'(?:[^\'\\\\]|\\\\.|\'\')*\'|0x[0-9a-fA-F]+(?![\w$])|\d+(?:\.\d+)?(?:[eE][-+]?\d+)?(?![\w$])|[\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, a quoted string, or a value from a placeholder. + * + * @param string $text Token. + * @return bool + */ + private static function is_literal( string $text ): bool { + return WpdbQueryVisitor::VALUE === $text || (bool) preg_match( '/^(?:\d|\'|"|(?:[xXbBnN]|_[A-Za-z0-9]+)\')/', $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 ); + } + + /** + * 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. + * + * @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. + * + * @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; + } +} diff --git a/tests/phpstan/base.neon b/tests/phpstan/base.neon index 1c102ca47e7da..8a246f8a12590 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