From 88a1415008e0308505c9a99a1e7b2bff8fdae04a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Viktor=20Sz=C3=A9pe?= Date: Tue, 20 Oct 2026 09:25:49 +0000 Subject: [PATCH 01/13] Preserve existing phpstan-return tags when applying function map --- src/Visitor.php | 11 +++++++++++ tests/VisitorTest.php | 27 +++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/Visitor.php b/src/Visitor.php index f15fc5a..b99b991 100644 --- a/src/Visitor.php +++ b/src/Visitor.php @@ -552,6 +552,17 @@ private function addStringTags(string $name, Doc $docComment): ?Doc $additions = $this->additionalTagStrings[$name]; $docCommentText = $docComment->getText(); + if (preg_match('/(?:^\h*\*|\/\*\*)\h*@phpstan-return\b/m', $docCommentText) === 1) { + $additions = array_filter( + $additions, + static fn (string $tag): bool => ! str_starts_with($tag, '@phpstan-return ') + ); + } + + if (count($additions) === 0) { + return null; + } + $newDocComment = sprintf( "%s\n * %s\n */", substr($docCommentText, 0, -self::WP_INDENT_SIZE), diff --git a/tests/VisitorTest.php b/tests/VisitorTest.php index a36c7b5..4cac654 100644 --- a/tests/VisitorTest.php +++ b/tests/VisitorTest.php @@ -67,6 +67,33 @@ function wpstubs_test_connector_with_phpstan_return( string $id ): ?array { ); } + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testMapReturnDoesNotOverrideExistingReturn(): void + { + $code = <<<'PHP' + Date: Tue, 20 Oct 2026 09:28:16 +0000 Subject: [PATCH 02/13] Use docblock parser to detect existing return tags --- src/Visitor.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/Visitor.php b/src/Visitor.php index b99b991..16cf16f 100644 --- a/src/Visitor.php +++ b/src/Visitor.php @@ -552,7 +552,13 @@ private function addStringTags(string $name, Doc $docComment): ?Doc $additions = $this->additionalTagStrings[$name]; $docCommentText = $docComment->getText(); - if (preg_match('/(?:^\h*\*|\/\*\*)\h*@phpstan-return\b/m', $docCommentText) === 1) { + try { + $docblock = $this->docBlockFactory->create($docCommentText); + } catch (\RuntimeException | \InvalidArgumentException $e) { + return null; + } + + if (count($docblock->getTagsByName('phpstan-return')) > 0) { $additions = array_filter( $additions, static fn (string $tag): bool => ! str_starts_with($tag, '@phpstan-return ') From c19dc8bc8a55e1cff65d32105cf24a3c329df32c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Viktor=20Sz=C3=A9pe?= Date: Tue, 20 Oct 2026 09:40:04 +0000 Subject: [PATCH 03/13] Regenerate stubs without duplicate mapped return tags --- src/Visitor.php | 4 +++- wordpress-stubs.php | 15 --------------- 2 files changed, 3 insertions(+), 16 deletions(-) diff --git a/src/Visitor.php b/src/Visitor.php index 16cf16f..a6dd986 100644 --- a/src/Visitor.php +++ b/src/Visitor.php @@ -561,7 +561,9 @@ private function addStringTags(string $name, Doc $docComment): ?Doc if (count($docblock->getTagsByName('phpstan-return')) > 0) { $additions = array_filter( $additions, - static fn (string $tag): bool => ! str_starts_with($tag, '@phpstan-return ') + static function (string $tag): bool { + return ! str_starts_with($tag, '@phpstan-return '); + } ); } diff --git a/wordpress-stubs.php b/wordpress-stubs.php index 9565127..c924d65 100644 --- a/wordpress-stubs.php +++ b/wordpress-stubs.php @@ -45004,7 +45004,6 @@ class WP_Http * filename: string|null, * http_response: WP_HTTP_Requests_Response|null, * } - * @phpstan-return array{headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary, body: string, response: array{code: int, message: string}, cookies: array, filename: string|null, http_response: \WP_HTTP_Requests_Response}|\WP_Error */ public function request($url, $args = array()) { @@ -50965,7 +50964,6 @@ public function rewind_comments() * @phpstan-return ( * $query is array{ fields: 'ids', ... } ? int[] : WP_Post[] * ) - * @phpstan-return ($query is array ? ($query is array{fields: 'id=>parent'|'ids', ...} ? array : array) : array|array) */ public function query($query) { @@ -130545,7 +130543,6 @@ function stripslashes_deep($value) * @phpstan-template T * @phpstan-param T|string $value * @phpstan-pure - * @phpstan-return ($value is string ? ($value is '' ? '' : string) : T) */ function stripslashes_from_strings_only($value) { @@ -132779,7 +132776,6 @@ function win_is_writable($path) * baseurl: non-empty-string, * } * |array{ error: non-empty-string } - * @phpstan-return array{path: string, url: string, subdir: string, basedir: string, baseurl: string, error: false|string} */ function wp_get_upload_dir() { @@ -132828,7 +132824,6 @@ function wp_get_upload_dir() * baseurl: non-empty-string, * } * |array{ error: non-empty-string } - * @phpstan-return array{path: string, url: string, subdir: string, basedir: string, baseurl: string, error: false|string} */ function wp_upload_dir($time = \null, $create_dir = \true, $refresh_cache = \false) { @@ -133158,7 +133153,6 @@ function wp_nonce_ays($action) * code?: string, * exit?: bool, * } $args - * @phpstan-return ($args is array{exit: false, ...} ? void : never) */ function wp_die($message = '', $title = '', $args = array()) { @@ -150588,7 +150582,6 @@ function auth_redirect() * as the function otherwise exits rather than returning false. * @phpstan-return ( $action is -1 ? int|false : int ) * @phpstan-param string $action - * @phpstan-return ($action is -1 ? 1|2|false : 1|2) */ function check_admin_referer($action = -1, $query_arg = '_wpnonce') { @@ -150610,7 +150603,6 @@ function check_admin_referer($action = -1, $query_arg = '_wpnonce') * as the function otherwise exits rather than returning false. * @phpstan-return ( $stop is true ? int : int|false ) * @phpstan-param string $action - * @phpstan-return ($stop is true ? 1|2 : 1|2|false) */ function check_ajax_referer($action = -1, $query_arg = \false, $stop = \true) { @@ -153294,7 +153286,6 @@ function get_post_type_object($post_type) * @return string[]|WP_Post_Type[] An array of post type names or objects. * @phpstan-return ( $output is 'names' ? string[] : WP_Post_Type[] ) * @phpstan-param 'names'|'objects' $output - * @phpstan-return ($output is 'names' ? array : array) */ function get_post_types($args = array(), $output = 'names', $operator = 'and') { @@ -154025,7 +154016,6 @@ function is_post_embeddable($post = \null) * w?: int, * year?: int, * } $args - * @phpstan-return ($args is array{fields: 'id=>parent'|'ids', ...} ? array : array) */ function get_posts($args = \null) { @@ -154298,7 +154288,6 @@ function sanitize_post($post, $context = 'display') * ) * @phpstan-template T of mixed * @phpstan-param T $value - * @phpstan-return ($field is 'ID'|'post_parent'|'menu_order' ? (T is int ? T : int) : ($field is 'ancestors' ? (T is array>|list> ? T : (T is list ? list> : array>)) : ($context is 'raw' ? T : ($context is 'attribute'|'js' ? string : ($context is 'edit' ? ($field is not 'post_content' ? string : mixed) : mixed))))) */ function sanitize_post_field($field, $value, $post_id, $context = 'display') { @@ -154823,7 +154812,6 @@ function wp_get_recent_posts($args = array(), $output = \ARRAY_A) * meta_input?: array, * page_template?: string, * } $postarr - * @phpstan-return ($wp_error is false ? int<0, max> : int<1, max>|\WP_Error) */ function wp_insert_post($postarr, $wp_error = \false, $fire_after_hooks = \true) { @@ -154876,7 +154864,6 @@ function wp_insert_post($postarr, $wp_error = \false, $fire_after_hooks = \true) * meta_input?: array, * page_template?: string, * } $postarr See wp_insert_post() - * @phpstan-return ($wp_error is false ? int<0, max> : int<1, max>|\WP_Error) */ function wp_update_post($postarr = array(), $wp_error = \false, $fire_after_hooks = \true) { @@ -155367,7 +155354,6 @@ function is_local_attachment($url) * @phpstan-return ( * $wp_error is false ? int : int|WP_Error * ) - * @phpstan-return ($wp_error is false ? int<0, max> : int<1, max>|\WP_Error) */ function wp_insert_attachment($args, $file = \false, $parent_post_id = 0, $wp_error = \false, $fire_after_hooks = \true) { @@ -161313,7 +161299,6 @@ function unregister_term_meta($taxonomy, $meta_key) * ) * ) * ) - * @phpstan-return ($term is 0 ? 0 : ($term is '' ? null : ($taxonomy is '' ? string|null : array{term_id: string, term_taxonomy_id: string}|null))) */ function term_exists($term, $taxonomy = '', $parent_term = \null) { From 7c32aeca37ad7defa54758674ff62a70a521c8b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Viktor=20Sz=C3=A9pe?= Date: Tue, 20 Oct 2026 15:10:16 +0000 Subject: [PATCH 04/13] Remove return type assertions for skipped map annotations --- tests/data/return/check-admin-referer.php | 12 ---- tests/data/return/check-ajax-referer.php | 16 ------ tests/data/return/get-post-types.php | 21 ------- tests/data/return/get-posts.php | 67 ----------------------- tests/data/return/sanitize-post-field.php | 59 -------------------- tests/data/return/stripslashes.php | 3 - tests/data/return/term-exists.php | 29 ---------- tests/data/return/wp-error-parameter.php | 48 ---------------- tests/data/return/wp-query.php | 23 -------- tests/data/return/wp-upload-dir.php | 4 -- 10 files changed, 282 deletions(-) delete mode 100644 tests/data/return/check-admin-referer.php delete mode 100644 tests/data/return/check-ajax-referer.php delete mode 100644 tests/data/return/get-post-types.php delete mode 100644 tests/data/return/get-posts.php diff --git a/tests/data/return/check-admin-referer.php b/tests/data/return/check-admin-referer.php deleted file mode 100644 index 7845b11..0000000 --- a/tests/data/return/check-admin-referer.php +++ /dev/null @@ -1,12 +0,0 @@ -', get_post_types([])); -assertType('array', get_post_types([], 'names')); - -// Objects output -assertType('array', get_post_types([], 'objects')); - -// Unknown string -assertType('array', get_post_types([], Faker::string())); - -// Unexpected output -assertType('array', get_post_types([], 'Hello')); diff --git a/tests/data/return/get-posts.php b/tests/data/return/get-posts.php deleted file mode 100644 index 32c6f3a..0000000 --- a/tests/data/return/get-posts.php +++ /dev/null @@ -1,67 +0,0 @@ -', get_posts()); -assertType('array', get_posts(['key' => 'value'])); -assertType('array', get_posts(['fields' => ''])); -assertType('array', get_posts(['fields' => 'ids'])); -assertType('array', get_posts(['fields' => 'id=>parent'])); -assertType('array', get_posts(['fields' => 'Hello'])); - -// Nonconstant array -assertType('array', get_posts(Faker::array())); - -// Unions -$union = Faker::union(['key' => 'value'], ['some' => 'thing']); -assertType('array', get_posts($union)); - -$union = Faker::union(['key' => 'value'], ['fields' => 'ids']); -assertType('array', get_posts($union)); - -$union = Faker::union(['key' => 'value'], ['fields' => '']); -assertType('array', get_posts($union)); - -$union = Faker::union(['key' => 'value'], ['fields' => 'id=>parent']); -assertType('array', get_posts($union)); - -$union = Faker::union(['fields' => ''], ['fields' => 'ids']); -assertType('array', get_posts($union)); - -$union = Faker::union(['fields' => ''], ['fields' => 'id=>parent']); -assertType('array', get_posts($union)); - -$union = Faker::union(['fields' => 'ids'], ['fields' => 'id=>parent']); -assertType('array', get_posts($union)); - -$union = Faker::union(Faker::array(), ['fields' => '']); -assertType('array', get_posts($union)); - -$union = Faker::union(Faker::array(), ['fields' => 'ids']); -assertType('array', get_posts($union)); - -$union = Faker::union(Faker::array(), ['fields' => 'id=>parent']); -assertType('array', get_posts($union)); - -$union = Faker::union(Faker::string(), ''); -assertType('array', get_posts(['fields' => $union])); - -$union = Faker::union(Faker::string(), 'ids'); -assertType('array', get_posts(['fields' => $union])); - -$union = Faker::union(Faker::string(), 'id=>parent'); -assertType('array', get_posts(['fields' => $union])); - -$union = Faker::union(Faker::string(), 'fields'); -assertType('array', get_posts([$union => ''])); - -$union = Faker::union(Faker::string(), 'fields'); -assertType('array', get_posts([$union => 'ids'])); - -$union = Faker::union(Faker::string(), 'fields'); -assertType('array', get_posts([$union => 'id=>parent'])); diff --git a/tests/data/return/sanitize-post-field.php b/tests/data/return/sanitize-post-field.php index f6f2e7f..0f52fc7 100644 --- a/tests/data/return/sanitize-post-field.php +++ b/tests/data/return/sanitize-post-field.php @@ -9,86 +9,27 @@ $postId = Faker::int(); -// Int fields => int - regardless of (non-constant) $value assertType('int', sanitize_post_field('ID', Faker::mixed(), $postId, 'raw')); assertType('int', sanitize_post_field('post_parent', Faker::mixed(), $postId, 'raw')); assertType('int', sanitize_post_field('menu_order', Faker::mixed(), $postId, 'raw')); -// Also in any other context assertType('int', sanitize_post_field('ID', Faker::mixed(), $postId, Faker::string())); -// But as-is if $value is int or int range -assertType('123', sanitize_post_field('ID', 123, $postId, 'raw')); -assertType('int<1, max>', sanitize_post_field('ID', Faker::positiveInt(), $postId, 'raw')); -assertType('123', sanitize_post_field('ID', 123, $postId, Faker::string())); -// Int array fields => array> - regardless of (non-constant) $value and $context assertType('array>', sanitize_post_field('ancestors', Faker::mixed(), $postId, Faker::string())); -// But as-is if $value is array> or list> - regardless of $context -assertType('array{41, 42, 43}', sanitize_post_field('ancestors', [41, 42, 43], $postId, Faker::string())); -assertType('array{foo: 42}', sanitize_post_field('ancestors', ['foo' => 42], $postId, Faker::string())); -// And retain list type - regardless of $context -assertType('array, int<0, max>>', sanitize_post_field('ancestors', Faker::list(), $postId, Faker::string())); -// All other constant fields: - -// In raw context => as-is -assertType("'field value'", sanitize_post_field('field', 'field value', $postId, 'raw')); -assertType('123', sanitize_post_field('field', 123, $postId, 'raw')); -assertType("array{foo: 'bar'}", sanitize_post_field('field', ['foo' => 'bar'], $postId, 'raw')); -assertType('true', sanitize_post_field('field', true, $postId, 'raw')); -assertType('bool', sanitize_post_field('field', Faker::bool(), $postId, 'raw')); -assertType('int', sanitize_post_field('field', Faker::int(), $postId, 'raw')); assertType('string', sanitize_post_field('field', Faker::string(), $postId, 'raw')); -// Field values in edit may be filtered to mixed, but are escaped using esc_html or esc_attr => string assertType('string', sanitize_post_field('field', 'field value', $postId, 'edit')); assertType('string', sanitize_post_field('field', Faker::string(), $postId, 'edit')); -// Except for field 'post_content' which is only escaped if ! user_can_richedit() -assertType('mixed', sanitize_post_field('post_content', 'field value', $postId, 'edit')); -assertType('mixed', sanitize_post_field('post_content', Faker::string(), $postId, 'edit')); -// Field values in attribute/js context are not filtered, but are escaped using esc_attr/esc_js -// => string, but not as given in the argument assertType('string', sanitize_post_field('field', 'field value', $postId, 'attribute')); assertType('string', sanitize_post_field('field', Faker::string(), $postId, 'attribute')); assertType('string', sanitize_post_field('field', 'field value', $postId, 'js')); assertType('string', sanitize_post_field('field', Faker::string(), $postId, 'js')); -// Field values in any other context may be filtered to mixed => mixed -assertType('mixed', sanitize_post_field('field', Faker::array(), $postId, 'db')); -assertType('mixed', sanitize_post_field('field', Faker::array(), $postId, 'display')); -assertType('mixed', sanitize_post_field('field', Faker::array(), $postId, 'rss')); -assertType('mixed', sanitize_post_field('field', Faker::bool(), $postId, 'db')); -assertType('mixed', sanitize_post_field('field', Faker::bool(), $postId, 'display')); -assertType('mixed', sanitize_post_field('field', Faker::bool(), $postId, 'rss')); -assertType('mixed', sanitize_post_field('field', Faker::int(), $postId, 'db')); -assertType('mixed', sanitize_post_field('field', Faker::int(), $postId, 'display')); -assertType('mixed', sanitize_post_field('field', Faker::int(), $postId, 'rss')); -assertType('mixed', sanitize_post_field('field', Faker::object(), $postId, 'db')); -assertType('mixed', sanitize_post_field('field', Faker::object(), $postId, 'display')); -assertType('mixed', sanitize_post_field('field', Faker::object(), $postId, 'rss')); -assertType('mixed', sanitize_post_field('field', Faker::string(), $postId, 'db')); -assertType('mixed', sanitize_post_field('field', Faker::string(), $postId, 'display')); -assertType('mixed', sanitize_post_field('field', Faker::string(), $postId, 'rss')); - -// Non constant field: - -// Non constant field in raw context => int (int field) or array> (int array field) or T (other field) -assertType("'field value'|array>|int", sanitize_post_field(Faker::string(), 'field value', $postId, 'raw')); assertType('array>|int|string', sanitize_post_field(Faker::string(), Faker::string(), $postId, 'raw')); -// Non constant field in attribute|js context -// => int (int field) or array> (int array field) or string (other field) assertType('array>|int|string', sanitize_post_field(Faker::string(), Faker::string(), $postId, 'attribute')); assertType('array>|int|string', sanitize_post_field(Faker::string(), Faker::string(), $postId, 'js')); -// Non constant field in attribute|js context than raw -// => int (int field) or array> (int array field) or string (other field) assertType('array>|int|string', sanitize_post_field(Faker::string(), Faker::string(), $postId, 'attribute')); assertType('array>|int|string', sanitize_post_field(Faker::string(), Faker::string(), $postId, 'js')); - -// Non constant field in any other context than attribute|js|raw => mixed -assertType('mixed', sanitize_post_field(Faker::string(), 123, $postId, 'db')); -assertType('mixed', sanitize_post_field(Faker::string(), 'field value', $postId, 'display')); -assertType('mixed', sanitize_post_field(Faker::string(), Faker::array(), $postId, 'rss')); -// And because of 'post_content': -assertType('mixed', sanitize_post_field(Faker::string(), Faker::string(), $postId, 'edit')); diff --git a/tests/data/return/stripslashes.php b/tests/data/return/stripslashes.php index ee28b72..fead077 100644 --- a/tests/data/return/stripslashes.php +++ b/tests/data/return/stripslashes.php @@ -15,9 +15,6 @@ assertType('int', stripslashes_from_strings_only(Faker::int())); assertType('1.23', stripslashes_from_strings_only(1.23)); assertType('float', stripslashes_from_strings_only(Faker::float())); -assertType("''", stripslashes_from_strings_only('')); -assertType('string', stripslashes_from_strings_only('value')); -assertType('string', stripslashes_from_strings_only(Faker::string())); assertType("array{key: 'value'}", stripslashes_from_strings_only(['key' => 'value'])); assertType('array', stripslashes_from_strings_only(Faker::array())); assertType('resource', stripslashes_from_strings_only(Faker::resource())); diff --git a/tests/data/return/term-exists.php b/tests/data/return/term-exists.php index a81b3ba..500b30d 100644 --- a/tests/data/return/term-exists.php +++ b/tests/data/return/term-exists.php @@ -12,41 +12,12 @@ $termInt = Faker::int(); $termIntStr = Faker::union(Faker::int(), Faker::string()); -// Empty taxonomy -assertType('string|null', term_exists(123)); -assertType('string|null', term_exists(123, '')); -assertType('string|null', term_exists($termStr)); -assertType('string|null', term_exists($termStr, '')); -assertType('0|string|null', term_exists($termInt)); -assertType('0|string|null', term_exists($termInt, '')); -assertType('0|string|null', term_exists($termIntStr)); -assertType('0|string|null', term_exists($termIntStr, '')); - -// Fixed taxonomy string -assertType('array{term_id: string, term_taxonomy_id: string}|null', term_exists(123, 'category')); -assertType('array{term_id: string, term_taxonomy_id: string}|null', term_exists($termStr, 'category')); -assertType('0|array{term_id: string, term_taxonomy_id: string}|null', term_exists($termInt, 'category')); -assertType('0|array{term_id: string, term_taxonomy_id: string}|null', term_exists($termIntStr, 'category')); - -// Unknown taxonomy type -$taxonomy = (string)$_GET['taxonomy'] ?? ''; -assertType('array{term_id: string, term_taxonomy_id: string}|string|null', term_exists(123, Faker::string())); -assertType('array{term_id: string, term_taxonomy_id: string}|string|null', term_exists($termStr, $taxonomy)); -assertType('0|array{term_id: string, term_taxonomy_id: string}|string|null', term_exists($termInt, Faker::string())); -assertType('0|array{term_id: string, term_taxonomy_id: string}|string|null', term_exists($termIntStr, Faker::string())); - // Term 0 assertType('0', term_exists(0)); assertType('0', term_exists(0, '')); assertType('0', term_exists(0, 'category')); assertType('0', term_exists(0, Faker::string())); -// Term empty string -assertType('null', term_exists('')); -assertType('null', term_exists('', '')); -assertType('null', term_exists('', 'category')); -assertType('null', term_exists('', Faker::string())); - // tag_exists() assertType('0', tag_exists(0)); assertType('null', tag_exists('')); diff --git a/tests/data/return/wp-error-parameter.php b/tests/data/return/wp-error-parameter.php index f221575..22695ee 100644 --- a/tests/data/return/wp-error-parameter.php +++ b/tests/data/return/wp-error-parameter.php @@ -5,9 +5,7 @@ namespace PhpStubs\WordPress\Core\Tests; use function wp_clear_scheduled_hook; -use function wp_insert_attachment; use function wp_insert_category; -use function wp_insert_post; use function wp_reschedule_event; use function wp_schedule_event; use function wp_schedule_single_event; @@ -15,7 +13,6 @@ use function wp_unschedule_event; use function wp_unschedule_hook; use function wp_update_comment; -use function wp_update_post; use function PHPStan\Testing\assertType; /* @@ -94,48 +91,3 @@ assertType('int<0, max>|false', wp_unschedule_hook('hook', false)); assertType('int<0, max>|WP_Error', wp_unschedule_hook('hook', true)); assertType('int<0, max>|WP_Error|false', wp_unschedule_hook('hook', Faker::bool())); - -/* - * wp_insert_post() - */ -assertType('int<0, max>', wp_insert_post([])); -assertType('int<0, max>', wp_insert_post([], false)); -assertType('int<0, max>', wp_insert_post([], false, true)); -assertType('int<0, max>', wp_insert_post([], false, false)); -assertType('int<1, max>|WP_Error', wp_insert_post([], true)); -assertType('int<1, max>|WP_Error', wp_insert_post([], true, true)); -assertType('int<1, max>|WP_Error', wp_insert_post([], true, false)); -assertType('int<0, max>|WP_Error', wp_insert_post([], Faker::bool())); -assertType('int<0, max>|WP_Error', wp_insert_post([], Faker::bool(), true)); -assertType('int<0, max>|WP_Error', wp_insert_post([], Faker::bool(), false)); - -/* - * wp_update_post() - */ -assertType('int<0, max>', wp_update_post([])); -assertType('int<0, max>', wp_update_post([], false)); -assertType('int<0, max>', wp_update_post([], false, true)); -assertType('int<0, max>', wp_update_post([], false, false)); -assertType('int<1, max>|WP_Error', wp_update_post([], true)); -assertType('int<1, max>|WP_Error', wp_update_post([], true, true)); -assertType('int<1, max>|WP_Error', wp_update_post([], true, false)); -assertType('int<0, max>|WP_Error', wp_update_post([], Faker::bool())); -assertType('int<0, max>|WP_Error', wp_update_post([], Faker::bool(), true)); -assertType('int<0, max>|WP_Error', wp_update_post([], Faker::bool(), false)); - -/* - * wp_insert_attachment() - */ -assertType('int<0, max>', wp_insert_attachment([])); -assertType('int<0, max>', wp_insert_attachment([], true)); -assertType('int<0, max>', wp_insert_attachment([], false)); -assertType('int<0, max>', wp_insert_attachment([], true, 1)); -assertType('int<0, max>', wp_insert_attachment([], true, 1, false)); -assertType('int<0, max>', wp_insert_attachment([], true, 1, false, false)); -assertType('int<0, max>', wp_insert_attachment([], true, 1, false, true)); -assertType('int<1, max>|WP_Error', wp_insert_attachment([], false, 0, true)); -assertType('int<1, max>|WP_Error', wp_insert_attachment([], false, 0, true, true)); -assertType('int<1, max>|WP_Error', wp_insert_attachment([], false, 0, true, false)); -assertType('int<0, max>|WP_Error', wp_insert_attachment([], true, 1, Faker::bool())); -assertType('int<0, max>|WP_Error', wp_insert_attachment([], true, 1, Faker::bool(), true)); -assertType('int<0, max>|WP_Error', wp_insert_attachment([], true, 1, Faker::bool(), false)); diff --git a/tests/data/return/wp-query.php b/tests/data/return/wp-query.php index 98e47d7..a10ab3e 100644 --- a/tests/data/return/wp-query.php +++ b/tests/data/return/wp-query.php @@ -18,29 +18,6 @@ assertType('bool|string', Faker::wpQuery()->query_vars_hash); assertType('null', Faker::wpQuery()->init_query_flags()); -// WP_Query::query(): default fields value. -assertType('array', Faker::wpQuery()->query([])); -assertType('array', Faker::wpQuery()->query(['fields' => ''])); -assertType('array', Faker::wpQuery()->query(['fields' => 'all'])); - -// WP_Query::query(): requesting IDs. -assertType('array', Faker::wpQuery()->query(['fields' => 'ids'])); -assertType('array', Faker::wpQuery()->query(['post_type' => 'page', 'fields' => 'ids'])); - -// WP_Query::query(): requesting parent IDs keyed by post ID. -assertType('array', Faker::wpQuery()->query(['fields' => 'id=>parent'])); - -// WP_Query::query(): unrecognized fields values fall back to post objects. -assertType('array', Faker::wpQuery()->query(['fields' => 'foo'])); - -// WP_Query::query(): unknown fields value. -assertType('array', Faker::wpQuery()->query(['fields' => Faker::string()])); - -// WP_Query::query(): a URL query string is parsed at runtime, so the fields -// value is not visible to PHPStan and every result shape stays possible. -assertType('array', Faker::wpQuery()->query('fields=ids')); -assertType('array', Faker::wpQuery()->query(Faker::string())); - // WP_Query::get_posts() reads the query vars off the instance instead of taking // them as an argument, so there is nothing to narrow the return type on. assertType('array', Faker::wpQuery()->get_posts()); diff --git a/tests/data/return/wp-upload-dir.php b/tests/data/return/wp-upload-dir.php index 9016b3b..fa06891 100644 --- a/tests/data/return/wp-upload-dir.php +++ b/tests/data/return/wp-upload-dir.php @@ -5,10 +5,6 @@ namespace PhpStubs\WordPress\Core\Tests; use function _wp_upload_dir; -use function wp_get_upload_dir; -use function wp_upload_dir; use function PHPStan\Testing\assertType; assertType('array{path: non-falsy-string, url: non-falsy-string, subdir: string, basedir: non-falsy-string, baseurl: non-falsy-string, error: false}', _wp_upload_dir()); -assertType('array{path: string, url: string, subdir: string, basedir: string, baseurl: string, error: string|false}', wp_get_upload_dir()); -assertType('array{path: string, url: string, subdir: string, basedir: string, baseurl: string, error: string|false}', wp_upload_dir()); From f49ee016902af9c3e915f5ed95656efe452b15a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Viktor=20Sz=C3=A9pe?= Date: Fri, 13 Nov 2026 13:58:23 +0000 Subject: [PATCH 05/13] Replace core PHPStan annotations with function map overrides --- composer.json | 1 + functionMap.php | 2 +- src/PhpStanTagMerger.php | 83 +++++++++++++++++++++ src/Visitor.php | 28 +------- tests/PhpStanTagMergerTest.php | 39 ++++++++++ tests/VisitorTest.php | 17 +++-- tests/data/return/check-admin-referer.php | 12 ++++ tests/data/return/check-ajax-referer.php | 16 +++++ tests/data/return/get-post-types.php | 21 ++++++ tests/data/return/get-posts.php | 67 +++++++++++++++++ tests/data/return/sanitize-post-field.php | 59 +++++++++++++++ tests/data/return/stripslashes.php | 3 + tests/data/return/term-exists.php | 29 ++++++++ tests/data/return/wp-error-parameter.php | 48 +++++++++++++ tests/data/return/wp-query.php | 23 ++++++ tests/data/return/wp-upload-dir.php | 4 ++ wordpress-stubs.php | 88 ++++------------------- 17 files changed, 435 insertions(+), 105 deletions(-) create mode 100644 src/PhpStanTagMerger.php create mode 100644 tests/PhpStanTagMergerTest.php create mode 100644 tests/data/return/check-admin-referer.php create mode 100644 tests/data/return/check-ajax-referer.php create mode 100644 tests/data/return/get-post-types.php create mode 100644 tests/data/return/get-posts.php diff --git a/composer.json b/composer.json index ab28256..0091c34 100644 --- a/composer.json +++ b/composer.json @@ -14,6 +14,7 @@ "nikic/php-parser": "^5.5", "php-stubs/generator": "^0.9", "phpdocumentor/reflection-docblock": "^6.0", + "phpstan/phpdoc-parser": "^2.3", "phpstan/phpstan": "^2.2", "phpunit/phpunit": "^9.5", "symfony/polyfill-php80": "*", diff --git a/functionMap.php b/functionMap.php index 6fe36ba..4ddf50e 100644 --- a/functionMap.php +++ b/functionMap.php @@ -216,7 +216,7 @@ 'single_tag_title' => ['($display is true ? void : string|void)'], 'single_term_title' => ['($display is true ? void : string|void)'], 'size_format' => ["(\$bytes is not numeric ? false : (\$bytes is int|'0' ? false : string))"], - 'stripslashes_from_strings_only' => ["(\$value is string ? (\$value is '' ? '' : string) : T)", '@phpstan-template T' => '', 'value' => 'T|string', '@phpstan-pure' => ''], + 'stripslashes_from_strings_only' => ["(\$value is string ? (\$value is '' ? '' : string) : T)", 'value' => 'T|string', '@phpstan-pure' => ''], 'switch_to_blog' => [null, 'deprecated' => 'null'], 'tag_exists' => ["(\$tag_name is 0 ? 0 : (\$tag_name is '' ? null : array{term_id: string, term_taxonomy_id: string}|null))"], 'taxonomy_exists' => ['($taxonomy is non-falsy-string ? bool : false)', '@phpstan-assert-if-true' => '=non-falsy-string $taxonomy'], diff --git a/src/PhpStanTagMerger.php b/src/PhpStanTagMerger.php new file mode 100644 index 0000000..13405c3 --- /dev/null +++ b/src/PhpStanTagMerger.php @@ -0,0 +1,83 @@ + $additions */ + public function merge(string $comment, array $additions): string + { + $config = new ParserConfig(['indexes' => true]); + $lexer = new Lexer($config); + $constExprParser = new ConstExprParser($config); + $parser = new PhpDocParser($config, new TypeParser($config, $constExprParser), $constExprParser); + $tokens = new TokenIterator($lexer->tokenize($comment)); + $original = $parser->parse($tokens); + $mapped = $parser->parse(new TokenIterator($lexer->tokenize(sprintf("/**\n * %s\n */", implode("\n * ", $additions))))); + $keys = array_map([$this, 'getTagKey'], $mapped->getTags()); + + $offset = 0; + $parts = []; + $rawTokens = $tokens->getTokens(); + foreach ($original->getTags() as $tag) { + if (! in_array($this->getTagKey($tag), $keys, true)) { + continue; + } + + $start = $tag->getAttribute(Attribute::START_INDEX); + $end = $tag->getAttribute(Attribute::END_INDEX); + assert(is_int($start) && is_int($end)); + if ($start > $offset && $rawTokens[$start - 1][Lexer::TYPE_OFFSET] === Lexer::TOKEN_PHPDOC_EOL) { + $start -= 1; + } + + $parts[] = $tokens->getContentBetween($offset, $start); + $offset = $end + 1; + } + $parts[] = $tokens->getContentBetween($offset, $tokens->getTokenCount()); + $comment = implode('', $parts); + $closing = strrpos($comment, '*/'); + assert($closing !== false); + + return sprintf("%s\n * %s\n */", rtrim(substr($comment, 0, $closing)), implode("\n * ", $additions)); + } + + private function getTagKey(PhpDoc\PhpDocTagNode $tag): string + { + $tagValue = $tag->value; + $target = ''; + if ($tagValue instanceof PhpDoc\ParamTagValueNode || $tagValue instanceof PhpDoc\ParamOutTagValueNode) { + $target = $tagValue->parameterName; + } elseif ($tagValue instanceof PhpDoc\TemplateTagValueNode) { + $target = $tagValue->name; + } elseif ($tagValue instanceof PhpDoc\PropertyTagValueNode) { + $target = $tagValue->propertyName; + } elseif ($tagValue instanceof PhpDoc\MethodTagValueNode) { + $target = $tagValue->methodName; + } elseif ($tagValue instanceof PhpDoc\TypeAliasTagValueNode) { + $target = $tagValue->alias; + } elseif ($tagValue instanceof PhpDoc\TypeAliasImportTagValueNode) { + $target = $tagValue->importedAs ?? $tagValue->importedAlias; + } elseif ($tagValue instanceof PhpDoc\ImplementsTagValueNode || $tagValue instanceof PhpDoc\ExtendsTagValueNode || $tagValue instanceof PhpDoc\UsesTagValueNode) { + $target = ltrim($tagValue->type->type->name, '\\'); + } elseif ($tagValue instanceof PhpDoc\AssertTagValueNode) { + $target = $tagValue->parameter; + } elseif ($tagValue instanceof PhpDoc\InvalidTagValueNode) { + // Do not replace unrelated malformed tags just because their names match. + $target = (string)$tagValue; + } + + return sprintf('%s:%s', $tag->name, $target); + } +} diff --git a/src/Visitor.php b/src/Visitor.php index a6dd986..173de43 100644 --- a/src/Visitor.php +++ b/src/Visitor.php @@ -549,33 +549,7 @@ private function addStringTags(string $name, Doc $docComment): ?Doc return null; } - $additions = $this->additionalTagStrings[$name]; - - $docCommentText = $docComment->getText(); - try { - $docblock = $this->docBlockFactory->create($docCommentText); - } catch (\RuntimeException | \InvalidArgumentException $e) { - return null; - } - - if (count($docblock->getTagsByName('phpstan-return')) > 0) { - $additions = array_filter( - $additions, - static function (string $tag): bool { - return ! str_starts_with($tag, '@phpstan-return '); - } - ); - } - - if (count($additions) === 0) { - return null; - } - - $newDocComment = sprintf( - "%s\n * %s\n */", - substr($docCommentText, 0, -self::WP_INDENT_SIZE), - implode("\n * ", $additions) - ); + $newDocComment = (new PhpStanTagMerger())->merge($docComment->getText(), $this->additionalTagStrings[$name]); return new Doc($newDocComment, $docComment->getStartLine(), $docComment->getStartFilePos()); } diff --git a/tests/PhpStanTagMergerTest.php b/tests/PhpStanTagMergerTest.php new file mode 100644 index 0000000..d26acd5 --- /dev/null +++ b/tests/PhpStanTagMergerTest.php @@ -0,0 +1,39 @@ +merge($comment, [$replacement]); + + self::assertStringNotContainsString(sprintf("\n * %s\n", $existing), $merged); + self::assertStringContainsString(sprintf("\n * %s\n", $replacement), $merged); + self::assertStringContainsString(sprintf("\n * %s\n", $unrelated), $merged); + self::assertStringContainsString("Description with `@phpstan-return` in prose.\n *\n * @since 1.0", $merged); + } + + /** @return iterable */ + public function tagOverrides(): iterable + { + yield 'multiline return' => ["@phpstan-return array{\n * id: int\n * }", '@phpstan-return array{id: positive-int}', '@return array The result.']; + yield 'parameter' => ['@phpstan-param int $first', '@phpstan-param positive-int $first', '@phpstan-param string $second']; + yield 'template' => ['@phpstan-template T of int', '@phpstan-template T of positive-int', '@phpstan-template U of string']; + yield 'property' => ['@phpstan-property-read int $first', '@phpstan-property-read positive-int $first', '@phpstan-property-read string $second']; + yield 'method' => ['@phpstan-method int first()', '@phpstan-method positive-int first()', '@phpstan-method string second()']; + yield 'alias' => ['@phpstan-type First int', '@phpstan-type First positive-int', '@phpstan-type Second string']; + yield 'import' => ['@phpstan-import-type First from OldClass', '@phpstan-import-type First from NewClass', '@phpstan-import-type Second from OldClass']; + yield 'interface' => ['@phpstan-implements \ArrayAccess', '@phpstan-implements ArrayAccess', '@phpstan-implements Iterator']; + yield 'assertion' => ['@phpstan-assert-if-true int $first', '@phpstan-assert-if-true positive-int $first', '@phpstan-assert-if-true string $second']; + } +} diff --git a/tests/VisitorTest.php b/tests/VisitorTest.php index 4cac654..99c32ee 100644 --- a/tests/VisitorTest.php +++ b/tests/VisitorTest.php @@ -71,12 +71,18 @@ function wpstubs_test_connector_with_phpstan_return( string $id ): ?array { * @runInSeparateProcess * @preserveGlobalState disabled */ - public function testMapReturnDoesNotOverrideExistingReturn(): void + public function testMapReturnOverridesExistingReturn(): void { $code = <<<'PHP' ', get_post_types([])); +assertType('array', get_post_types([], 'names')); + +// Objects output +assertType('array', get_post_types([], 'objects')); + +// Unknown string +assertType('array', get_post_types([], Faker::string())); + +// Unexpected output +assertType('array', get_post_types([], 'Hello')); diff --git a/tests/data/return/get-posts.php b/tests/data/return/get-posts.php new file mode 100644 index 0000000..32c6f3a --- /dev/null +++ b/tests/data/return/get-posts.php @@ -0,0 +1,67 @@ +', get_posts()); +assertType('array', get_posts(['key' => 'value'])); +assertType('array', get_posts(['fields' => ''])); +assertType('array', get_posts(['fields' => 'ids'])); +assertType('array', get_posts(['fields' => 'id=>parent'])); +assertType('array', get_posts(['fields' => 'Hello'])); + +// Nonconstant array +assertType('array', get_posts(Faker::array())); + +// Unions +$union = Faker::union(['key' => 'value'], ['some' => 'thing']); +assertType('array', get_posts($union)); + +$union = Faker::union(['key' => 'value'], ['fields' => 'ids']); +assertType('array', get_posts($union)); + +$union = Faker::union(['key' => 'value'], ['fields' => '']); +assertType('array', get_posts($union)); + +$union = Faker::union(['key' => 'value'], ['fields' => 'id=>parent']); +assertType('array', get_posts($union)); + +$union = Faker::union(['fields' => ''], ['fields' => 'ids']); +assertType('array', get_posts($union)); + +$union = Faker::union(['fields' => ''], ['fields' => 'id=>parent']); +assertType('array', get_posts($union)); + +$union = Faker::union(['fields' => 'ids'], ['fields' => 'id=>parent']); +assertType('array', get_posts($union)); + +$union = Faker::union(Faker::array(), ['fields' => '']); +assertType('array', get_posts($union)); + +$union = Faker::union(Faker::array(), ['fields' => 'ids']); +assertType('array', get_posts($union)); + +$union = Faker::union(Faker::array(), ['fields' => 'id=>parent']); +assertType('array', get_posts($union)); + +$union = Faker::union(Faker::string(), ''); +assertType('array', get_posts(['fields' => $union])); + +$union = Faker::union(Faker::string(), 'ids'); +assertType('array', get_posts(['fields' => $union])); + +$union = Faker::union(Faker::string(), 'id=>parent'); +assertType('array', get_posts(['fields' => $union])); + +$union = Faker::union(Faker::string(), 'fields'); +assertType('array', get_posts([$union => ''])); + +$union = Faker::union(Faker::string(), 'fields'); +assertType('array', get_posts([$union => 'ids'])); + +$union = Faker::union(Faker::string(), 'fields'); +assertType('array', get_posts([$union => 'id=>parent'])); diff --git a/tests/data/return/sanitize-post-field.php b/tests/data/return/sanitize-post-field.php index 0f52fc7..f6f2e7f 100644 --- a/tests/data/return/sanitize-post-field.php +++ b/tests/data/return/sanitize-post-field.php @@ -9,27 +9,86 @@ $postId = Faker::int(); +// Int fields => int - regardless of (non-constant) $value assertType('int', sanitize_post_field('ID', Faker::mixed(), $postId, 'raw')); assertType('int', sanitize_post_field('post_parent', Faker::mixed(), $postId, 'raw')); assertType('int', sanitize_post_field('menu_order', Faker::mixed(), $postId, 'raw')); +// Also in any other context assertType('int', sanitize_post_field('ID', Faker::mixed(), $postId, Faker::string())); +// But as-is if $value is int or int range +assertType('123', sanitize_post_field('ID', 123, $postId, 'raw')); +assertType('int<1, max>', sanitize_post_field('ID', Faker::positiveInt(), $postId, 'raw')); +assertType('123', sanitize_post_field('ID', 123, $postId, Faker::string())); +// Int array fields => array> - regardless of (non-constant) $value and $context assertType('array>', sanitize_post_field('ancestors', Faker::mixed(), $postId, Faker::string())); +// But as-is if $value is array> or list> - regardless of $context +assertType('array{41, 42, 43}', sanitize_post_field('ancestors', [41, 42, 43], $postId, Faker::string())); +assertType('array{foo: 42}', sanitize_post_field('ancestors', ['foo' => 42], $postId, Faker::string())); +// And retain list type - regardless of $context +assertType('array, int<0, max>>', sanitize_post_field('ancestors', Faker::list(), $postId, Faker::string())); +// All other constant fields: + +// In raw context => as-is +assertType("'field value'", sanitize_post_field('field', 'field value', $postId, 'raw')); +assertType('123', sanitize_post_field('field', 123, $postId, 'raw')); +assertType("array{foo: 'bar'}", sanitize_post_field('field', ['foo' => 'bar'], $postId, 'raw')); +assertType('true', sanitize_post_field('field', true, $postId, 'raw')); +assertType('bool', sanitize_post_field('field', Faker::bool(), $postId, 'raw')); +assertType('int', sanitize_post_field('field', Faker::int(), $postId, 'raw')); assertType('string', sanitize_post_field('field', Faker::string(), $postId, 'raw')); +// Field values in edit may be filtered to mixed, but are escaped using esc_html or esc_attr => string assertType('string', sanitize_post_field('field', 'field value', $postId, 'edit')); assertType('string', sanitize_post_field('field', Faker::string(), $postId, 'edit')); +// Except for field 'post_content' which is only escaped if ! user_can_richedit() +assertType('mixed', sanitize_post_field('post_content', 'field value', $postId, 'edit')); +assertType('mixed', sanitize_post_field('post_content', Faker::string(), $postId, 'edit')); +// Field values in attribute/js context are not filtered, but are escaped using esc_attr/esc_js +// => string, but not as given in the argument assertType('string', sanitize_post_field('field', 'field value', $postId, 'attribute')); assertType('string', sanitize_post_field('field', Faker::string(), $postId, 'attribute')); assertType('string', sanitize_post_field('field', 'field value', $postId, 'js')); assertType('string', sanitize_post_field('field', Faker::string(), $postId, 'js')); +// Field values in any other context may be filtered to mixed => mixed +assertType('mixed', sanitize_post_field('field', Faker::array(), $postId, 'db')); +assertType('mixed', sanitize_post_field('field', Faker::array(), $postId, 'display')); +assertType('mixed', sanitize_post_field('field', Faker::array(), $postId, 'rss')); +assertType('mixed', sanitize_post_field('field', Faker::bool(), $postId, 'db')); +assertType('mixed', sanitize_post_field('field', Faker::bool(), $postId, 'display')); +assertType('mixed', sanitize_post_field('field', Faker::bool(), $postId, 'rss')); +assertType('mixed', sanitize_post_field('field', Faker::int(), $postId, 'db')); +assertType('mixed', sanitize_post_field('field', Faker::int(), $postId, 'display')); +assertType('mixed', sanitize_post_field('field', Faker::int(), $postId, 'rss')); +assertType('mixed', sanitize_post_field('field', Faker::object(), $postId, 'db')); +assertType('mixed', sanitize_post_field('field', Faker::object(), $postId, 'display')); +assertType('mixed', sanitize_post_field('field', Faker::object(), $postId, 'rss')); +assertType('mixed', sanitize_post_field('field', Faker::string(), $postId, 'db')); +assertType('mixed', sanitize_post_field('field', Faker::string(), $postId, 'display')); +assertType('mixed', sanitize_post_field('field', Faker::string(), $postId, 'rss')); + +// Non constant field: + +// Non constant field in raw context => int (int field) or array> (int array field) or T (other field) +assertType("'field value'|array>|int", sanitize_post_field(Faker::string(), 'field value', $postId, 'raw')); assertType('array>|int|string', sanitize_post_field(Faker::string(), Faker::string(), $postId, 'raw')); +// Non constant field in attribute|js context +// => int (int field) or array> (int array field) or string (other field) assertType('array>|int|string', sanitize_post_field(Faker::string(), Faker::string(), $postId, 'attribute')); assertType('array>|int|string', sanitize_post_field(Faker::string(), Faker::string(), $postId, 'js')); +// Non constant field in attribute|js context than raw +// => int (int field) or array> (int array field) or string (other field) assertType('array>|int|string', sanitize_post_field(Faker::string(), Faker::string(), $postId, 'attribute')); assertType('array>|int|string', sanitize_post_field(Faker::string(), Faker::string(), $postId, 'js')); + +// Non constant field in any other context than attribute|js|raw => mixed +assertType('mixed', sanitize_post_field(Faker::string(), 123, $postId, 'db')); +assertType('mixed', sanitize_post_field(Faker::string(), 'field value', $postId, 'display')); +assertType('mixed', sanitize_post_field(Faker::string(), Faker::array(), $postId, 'rss')); +// And because of 'post_content': +assertType('mixed', sanitize_post_field(Faker::string(), Faker::string(), $postId, 'edit')); diff --git a/tests/data/return/stripslashes.php b/tests/data/return/stripslashes.php index fead077..ee28b72 100644 --- a/tests/data/return/stripslashes.php +++ b/tests/data/return/stripslashes.php @@ -15,6 +15,9 @@ assertType('int', stripslashes_from_strings_only(Faker::int())); assertType('1.23', stripslashes_from_strings_only(1.23)); assertType('float', stripslashes_from_strings_only(Faker::float())); +assertType("''", stripslashes_from_strings_only('')); +assertType('string', stripslashes_from_strings_only('value')); +assertType('string', stripslashes_from_strings_only(Faker::string())); assertType("array{key: 'value'}", stripslashes_from_strings_only(['key' => 'value'])); assertType('array', stripslashes_from_strings_only(Faker::array())); assertType('resource', stripslashes_from_strings_only(Faker::resource())); diff --git a/tests/data/return/term-exists.php b/tests/data/return/term-exists.php index 500b30d..a81b3ba 100644 --- a/tests/data/return/term-exists.php +++ b/tests/data/return/term-exists.php @@ -12,12 +12,41 @@ $termInt = Faker::int(); $termIntStr = Faker::union(Faker::int(), Faker::string()); +// Empty taxonomy +assertType('string|null', term_exists(123)); +assertType('string|null', term_exists(123, '')); +assertType('string|null', term_exists($termStr)); +assertType('string|null', term_exists($termStr, '')); +assertType('0|string|null', term_exists($termInt)); +assertType('0|string|null', term_exists($termInt, '')); +assertType('0|string|null', term_exists($termIntStr)); +assertType('0|string|null', term_exists($termIntStr, '')); + +// Fixed taxonomy string +assertType('array{term_id: string, term_taxonomy_id: string}|null', term_exists(123, 'category')); +assertType('array{term_id: string, term_taxonomy_id: string}|null', term_exists($termStr, 'category')); +assertType('0|array{term_id: string, term_taxonomy_id: string}|null', term_exists($termInt, 'category')); +assertType('0|array{term_id: string, term_taxonomy_id: string}|null', term_exists($termIntStr, 'category')); + +// Unknown taxonomy type +$taxonomy = (string)$_GET['taxonomy'] ?? ''; +assertType('array{term_id: string, term_taxonomy_id: string}|string|null', term_exists(123, Faker::string())); +assertType('array{term_id: string, term_taxonomy_id: string}|string|null', term_exists($termStr, $taxonomy)); +assertType('0|array{term_id: string, term_taxonomy_id: string}|string|null', term_exists($termInt, Faker::string())); +assertType('0|array{term_id: string, term_taxonomy_id: string}|string|null', term_exists($termIntStr, Faker::string())); + // Term 0 assertType('0', term_exists(0)); assertType('0', term_exists(0, '')); assertType('0', term_exists(0, 'category')); assertType('0', term_exists(0, Faker::string())); +// Term empty string +assertType('null', term_exists('')); +assertType('null', term_exists('', '')); +assertType('null', term_exists('', 'category')); +assertType('null', term_exists('', Faker::string())); + // tag_exists() assertType('0', tag_exists(0)); assertType('null', tag_exists('')); diff --git a/tests/data/return/wp-error-parameter.php b/tests/data/return/wp-error-parameter.php index 22695ee..f221575 100644 --- a/tests/data/return/wp-error-parameter.php +++ b/tests/data/return/wp-error-parameter.php @@ -5,7 +5,9 @@ namespace PhpStubs\WordPress\Core\Tests; use function wp_clear_scheduled_hook; +use function wp_insert_attachment; use function wp_insert_category; +use function wp_insert_post; use function wp_reschedule_event; use function wp_schedule_event; use function wp_schedule_single_event; @@ -13,6 +15,7 @@ use function wp_unschedule_event; use function wp_unschedule_hook; use function wp_update_comment; +use function wp_update_post; use function PHPStan\Testing\assertType; /* @@ -91,3 +94,48 @@ assertType('int<0, max>|false', wp_unschedule_hook('hook', false)); assertType('int<0, max>|WP_Error', wp_unschedule_hook('hook', true)); assertType('int<0, max>|WP_Error|false', wp_unschedule_hook('hook', Faker::bool())); + +/* + * wp_insert_post() + */ +assertType('int<0, max>', wp_insert_post([])); +assertType('int<0, max>', wp_insert_post([], false)); +assertType('int<0, max>', wp_insert_post([], false, true)); +assertType('int<0, max>', wp_insert_post([], false, false)); +assertType('int<1, max>|WP_Error', wp_insert_post([], true)); +assertType('int<1, max>|WP_Error', wp_insert_post([], true, true)); +assertType('int<1, max>|WP_Error', wp_insert_post([], true, false)); +assertType('int<0, max>|WP_Error', wp_insert_post([], Faker::bool())); +assertType('int<0, max>|WP_Error', wp_insert_post([], Faker::bool(), true)); +assertType('int<0, max>|WP_Error', wp_insert_post([], Faker::bool(), false)); + +/* + * wp_update_post() + */ +assertType('int<0, max>', wp_update_post([])); +assertType('int<0, max>', wp_update_post([], false)); +assertType('int<0, max>', wp_update_post([], false, true)); +assertType('int<0, max>', wp_update_post([], false, false)); +assertType('int<1, max>|WP_Error', wp_update_post([], true)); +assertType('int<1, max>|WP_Error', wp_update_post([], true, true)); +assertType('int<1, max>|WP_Error', wp_update_post([], true, false)); +assertType('int<0, max>|WP_Error', wp_update_post([], Faker::bool())); +assertType('int<0, max>|WP_Error', wp_update_post([], Faker::bool(), true)); +assertType('int<0, max>|WP_Error', wp_update_post([], Faker::bool(), false)); + +/* + * wp_insert_attachment() + */ +assertType('int<0, max>', wp_insert_attachment([])); +assertType('int<0, max>', wp_insert_attachment([], true)); +assertType('int<0, max>', wp_insert_attachment([], false)); +assertType('int<0, max>', wp_insert_attachment([], true, 1)); +assertType('int<0, max>', wp_insert_attachment([], true, 1, false)); +assertType('int<0, max>', wp_insert_attachment([], true, 1, false, false)); +assertType('int<0, max>', wp_insert_attachment([], true, 1, false, true)); +assertType('int<1, max>|WP_Error', wp_insert_attachment([], false, 0, true)); +assertType('int<1, max>|WP_Error', wp_insert_attachment([], false, 0, true, true)); +assertType('int<1, max>|WP_Error', wp_insert_attachment([], false, 0, true, false)); +assertType('int<0, max>|WP_Error', wp_insert_attachment([], true, 1, Faker::bool())); +assertType('int<0, max>|WP_Error', wp_insert_attachment([], true, 1, Faker::bool(), true)); +assertType('int<0, max>|WP_Error', wp_insert_attachment([], true, 1, Faker::bool(), false)); diff --git a/tests/data/return/wp-query.php b/tests/data/return/wp-query.php index a10ab3e..98e47d7 100644 --- a/tests/data/return/wp-query.php +++ b/tests/data/return/wp-query.php @@ -18,6 +18,29 @@ assertType('bool|string', Faker::wpQuery()->query_vars_hash); assertType('null', Faker::wpQuery()->init_query_flags()); +// WP_Query::query(): default fields value. +assertType('array', Faker::wpQuery()->query([])); +assertType('array', Faker::wpQuery()->query(['fields' => ''])); +assertType('array', Faker::wpQuery()->query(['fields' => 'all'])); + +// WP_Query::query(): requesting IDs. +assertType('array', Faker::wpQuery()->query(['fields' => 'ids'])); +assertType('array', Faker::wpQuery()->query(['post_type' => 'page', 'fields' => 'ids'])); + +// WP_Query::query(): requesting parent IDs keyed by post ID. +assertType('array', Faker::wpQuery()->query(['fields' => 'id=>parent'])); + +// WP_Query::query(): unrecognized fields values fall back to post objects. +assertType('array', Faker::wpQuery()->query(['fields' => 'foo'])); + +// WP_Query::query(): unknown fields value. +assertType('array', Faker::wpQuery()->query(['fields' => Faker::string()])); + +// WP_Query::query(): a URL query string is parsed at runtime, so the fields +// value is not visible to PHPStan and every result shape stays possible. +assertType('array', Faker::wpQuery()->query('fields=ids')); +assertType('array', Faker::wpQuery()->query(Faker::string())); + // WP_Query::get_posts() reads the query vars off the instance instead of taking // them as an argument, so there is nothing to narrow the return type on. assertType('array', Faker::wpQuery()->get_posts()); diff --git a/tests/data/return/wp-upload-dir.php b/tests/data/return/wp-upload-dir.php index fa06891..9016b3b 100644 --- a/tests/data/return/wp-upload-dir.php +++ b/tests/data/return/wp-upload-dir.php @@ -5,6 +5,10 @@ namespace PhpStubs\WordPress\Core\Tests; use function _wp_upload_dir; +use function wp_get_upload_dir; +use function wp_upload_dir; use function PHPStan\Testing\assertType; assertType('array{path: non-falsy-string, url: non-falsy-string, subdir: string, basedir: non-falsy-string, baseurl: non-falsy-string, error: false}', _wp_upload_dir()); +assertType('array{path: string, url: string, subdir: string, basedir: string, baseurl: string, error: string|false}', wp_get_upload_dir()); +assertType('array{path: string, url: string, subdir: string, basedir: string, baseurl: string, error: string|false}', wp_upload_dir()); diff --git a/wordpress-stubs.php b/wordpress-stubs.php index c924d65..f0ce4d7 100644 --- a/wordpress-stubs.php +++ b/wordpress-stubs.php @@ -44993,17 +44993,7 @@ class WP_Http * filename?: string, * limit_response_size?: int, * } $args - * @phpstan-return \WP_Error|array{ - * headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary, - * body: string, - * response: array{ - * code: int|false, - * message: string|false, - * }, - * cookies: WP_Http_Cookie[], - * filename: string|null, - * http_response: WP_HTTP_Requests_Response|null, - * } + * @phpstan-return array{headers: \WpOrg\Requests\Utility\CaseInsensitiveDictionary, body: string, response: array{code: int, message: string}, cookies: array, filename: string|null, http_response: \WP_HTTP_Requests_Response}|\WP_Error */ public function request($url, $args = array()) { @@ -50961,9 +50951,7 @@ public function rewind_comments() * @param string|array $query URL query string or array of query arguments. * @return WP_Post[]|int[] Array of post objects or post IDs. * - * @phpstan-return ( - * $query is array{ fields: 'ids', ... } ? int[] : WP_Post[] - * ) + * @phpstan-return ($query is array ? ($query is array{fields: 'id=>parent'|'ids', ...} ? array : array) : array|array) */ public function query($query) { @@ -107651,10 +107639,6 @@ function add_settings_section($id, $title, $callback, $page, $args = array()) * @type string $class CSS Class to be added to the `` element when the * field is output. * } - * @phpstan-param array{ - * label_for?: string, - * class?: string, - * } $args * @phpstan-param array{label_for?: string, class?: string, ...} $args * @phpstan-return void */ @@ -120904,9 +120888,6 @@ function has_term($term = '', $taxonomy = '', $post = \null) * @type string $taxonomy Taxonomy to retrieve terms for. Default 'category'. * } * @return array List of category objects. - * @phpstan-param array{ - * taxonomy?: string, - * } $args * @phpstan-param array{taxonomy?:string,...} $args * @phpstan-return ($args is array{fields: 'count', ...} ? list : ($args is array{fields: 'names'|'slugs', ...} ? list : ($args is array{fields: 'id=>name'|'id=>slug', ...} ? array : ($args is array{fields: 'id=>parent', ...} ? array : ($args is array{fields: 'ids'|'tt_ids', ...} ? list : array))))) */ @@ -130538,11 +130519,9 @@ function stripslashes_deep($value) * @return mixed The stripped value. * * @phpstan-template T - * @phpstan-param T $value - * @phpstan-return (T is string ? string : T) - * @phpstan-template T * @phpstan-param T|string $value * @phpstan-pure + * @phpstan-return ($value is string ? ($value is '' ? '' : string) : T) */ function stripslashes_from_strings_only($value) { @@ -132768,14 +132747,7 @@ function win_is_writable($path) * @see wp_upload_dir() * * @return array See wp_upload_dir() for description. - * @phpstan-return array{ - * path: non-empty-string, - * url: non-empty-string, - * subdir: non-empty-string, - * basedir: non-empty-string, - * baseurl: non-empty-string, - * } - * |array{ error: non-empty-string } + * @phpstan-return array{path: string, url: string, subdir: string, basedir: string, baseurl: string, error: false|string} */ function wp_get_upload_dir() { @@ -132816,14 +132788,7 @@ function wp_get_upload_dir() * @type string $baseurl URL path without subdir. * @type string|false $error False or error message. * } - * @phpstan-return array{ - * path: non-empty-string, - * url: non-empty-string, - * subdir: non-empty-string, - * basedir: non-empty-string, - * baseurl: non-empty-string, - * } - * |array{ error: non-empty-string } + * @phpstan-return array{path: string, url: string, subdir: string, basedir: string, baseurl: string, error: false|string} */ function wp_upload_dir($time = \null, $create_dir = \true, $refresh_cache = \false) { @@ -133142,7 +133107,6 @@ function wp_nonce_ays($action) * } * @return void Never returns if `$args['exit']` is true (the default), otherwise returns void. * @phpstan-param string|WP_Error|int<-1, max> $message - * @phpstan-return ( $args is array{exit: false} ? void : never ) * @phpstan-param int|array{ * response?: int, * link_url?: string, @@ -133153,6 +133117,7 @@ function wp_nonce_ays($action) * code?: string, * exit?: bool, * } $args + * @phpstan-return ($args is array{exit: false, ...} ? void : never) */ function wp_die($message = '', $title = '', $args = array()) { @@ -150580,8 +150545,8 @@ function auth_redirect() * 2 if the nonce is valid and generated between 12-24 hours ago. * False if the nonce is invalid. Only possible when `$action` is -1, * as the function otherwise exits rather than returning false. - * @phpstan-return ( $action is -1 ? int|false : int ) * @phpstan-param string $action + * @phpstan-return ($action is -1 ? 1|2|false : 1|2) */ function check_admin_referer($action = -1, $query_arg = '_wpnonce') { @@ -150601,8 +150566,8 @@ function check_admin_referer($action = -1, $query_arg = '_wpnonce') * 2 if the nonce is valid and generated between 12-24 hours ago. * False if the nonce is invalid. Only possible when `$stop` is false, * as the function otherwise exits rather than returning false. - * @phpstan-return ( $stop is true ? int : int|false ) * @phpstan-param string $action + * @phpstan-return ($stop is true ? 1|2 : 1|2|false) */ function check_ajax_referer($action = -1, $query_arg = \false, $stop = \true) { @@ -153284,8 +153249,8 @@ function get_post_type_object($post_type) * element from the array needs to match; 'and' means all elements * must match; 'not' means no elements may match. Default 'and'. * @return string[]|WP_Post_Type[] An array of post type names or objects. - * @phpstan-return ( $output is 'names' ? string[] : WP_Post_Type[] ) * @phpstan-param 'names'|'objects' $output + * @phpstan-return ($output is 'names' ? array : array) */ function get_post_types($args = array(), $output = 'names', $operator = 'and') { @@ -153932,9 +153897,6 @@ function is_post_embeddable($post = \null) * } * @return WP_Post[]|int[] Array of post objects or post IDs. * - * @phpstan-return ( - * $args is array{ fields: 'ids', ... } ? int[] : WP_Post[] - * ) * @phpstan-param array{ * numberposts?: int, * category?: int|string, @@ -154016,6 +153978,7 @@ function is_post_embeddable($post = \null) * w?: int, * year?: int, * } $args + * @phpstan-return ($args is array{fields: 'id=>parent'|'ids', ...} ? array : array) */ function get_posts($args = \null) { @@ -154281,13 +154244,9 @@ function sanitize_post($post, $context = 'display') * @return mixed Sanitized value. * * @phpstan-param 'raw'|'edit'|'db'|'display'|'attribute'|'js'|'sample' $context - * @phpstan-return ( - * $field is 'ID'|'post_parent'|'menu_order' ? int : ( - * $field is 'ancestors' ? non-negative-int[] : string - * ) - * ) * @phpstan-template T of mixed * @phpstan-param T $value + * @phpstan-return ($field is 'ID'|'post_parent'|'menu_order' ? (T is int ? T : int) : ($field is 'ancestors' ? (T is array>|list> ? T : (T is list ? list> : array>)) : ($context is 'raw' ? T : ($context is 'attribute'|'js' ? string : ($context is 'edit' ? ($field is not 'post_content' ? string : mixed) : mixed))))) */ function sanitize_post_field($field, $value, $post_id, $context = 'display') { @@ -154781,9 +154740,6 @@ function wp_get_recent_posts($args = array(), $output = \ARRAY_A) * @param bool $fire_after_hooks Optional. Whether to fire the after insert hooks. Default true. * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure. * - * @phpstan-return ( - * $wp_error is false ? int : int|WP_Error - * ) * @phpstan-param array{ * ID?: int, * post_author?: int, @@ -154812,6 +154768,7 @@ function wp_get_recent_posts($args = array(), $output = \ARRAY_A) * meta_input?: array, * page_template?: string, * } $postarr + * @phpstan-return ($wp_error is false ? int<0, max> : int<1, max>|\WP_Error) */ function wp_insert_post($postarr, $wp_error = \false, $fire_after_hooks = \true) { @@ -154833,9 +154790,6 @@ function wp_insert_post($postarr, $wp_error = \false, $fire_after_hooks = \true) * @param bool $fire_after_hooks Optional. Whether to fire the after insert hooks. Default true. * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure. * - * @phpstan-return ( - * $wp_error is false ? int : int|WP_Error - * ) * @phpstan-param array{ * ID?: int, * post_author?: int, @@ -154864,6 +154818,7 @@ function wp_insert_post($postarr, $wp_error = \false, $fire_after_hooks = \true) * meta_input?: array, * page_template?: string, * } $postarr See wp_insert_post() + * @phpstan-return ($wp_error is false ? int<0, max> : int<1, max>|\WP_Error) */ function wp_update_post($postarr = array(), $wp_error = \false, $fire_after_hooks = \true) { @@ -155351,9 +155306,7 @@ function is_local_attachment($url) * @param bool $fire_after_hooks Optional. Whether to fire the after insert hooks. Default true. * @return int|WP_Error The attachment ID on success. The value 0 or WP_Error on failure. * - * @phpstan-return ( - * $wp_error is false ? int : int|WP_Error - * ) + * @phpstan-return ($wp_error is false ? int<0, max> : int<1, max>|\WP_Error) */ function wp_insert_attachment($args, $file = \false, $parent_post_id = 0, $wp_error = \false, $fire_after_hooks = \true) { @@ -161287,18 +161240,7 @@ function unregister_term_meta($taxonomy, $meta_key) * Returns an array of the term ID and the term taxonomy ID if the taxonomy is specified and the pairing exists. * Returns 0 if term ID 0 is passed to the function. * - * @phpstan-return ( - * $term is null ? null : ( - * $term is 0 ? 0 : ( - * $taxonomy is '' ? int|null : ( - * array{ - * term_id: numeric-string, - * term_taxonomy_id: numeric-string, - * }|null - * ) - * ) - * ) - * ) + * @phpstan-return ($term is 0 ? 0 : ($term is '' ? null : ($taxonomy is '' ? string|null : array{term_id: string, term_taxonomy_id: string}|null))) */ function term_exists($term, $taxonomy = '', $parent_term = \null) { From b10fee5d46430424d6b383effa2041ca9bb4565c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Viktor=20Sz=C3=A9pe?= Date: Fri, 13 Nov 2026 15:10:19 +0000 Subject: [PATCH 06/13] Log core and mapped PHPStan annotations when overriding tags --- src/PhpStanTagMerger.php | 20 ++++++++++++++++---- src/Visitor.php | 9 ++++++++- tests/VisitorTest.php | 18 +++++++++++++++++- 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/src/PhpStanTagMerger.php b/src/PhpStanTagMerger.php index 13405c3..be8651f 100644 --- a/src/PhpStanTagMerger.php +++ b/src/PhpStanTagMerger.php @@ -15,8 +15,11 @@ final class PhpStanTagMerger { - /** @param list $additions */ - public function merge(string $comment, array $additions): string + /** + * @param list $additions + * @param callable(string, string): void|null $onOverride + */ + public function merge(string $comment, array $additions, ?callable $onOverride = null): string { $config = new ParserConfig(['indexes' => true]); $lexer = new Lexer($config); @@ -25,16 +28,25 @@ public function merge(string $comment, array $additions): string $tokens = new TokenIterator($lexer->tokenize($comment)); $original = $parser->parse($tokens); $mapped = $parser->parse(new TokenIterator($lexer->tokenize(sprintf("/**\n * %s\n */", implode("\n * ", $additions))))); - $keys = array_map([$this, 'getTagKey'], $mapped->getTags()); + $replacements = []; + foreach ($mapped->getTags() as $tag) { + $replacements[$this->getTagKey($tag)] = (string)$tag; + } $offset = 0; $parts = []; $rawTokens = $tokens->getTokens(); foreach ($original->getTags() as $tag) { - if (! in_array($this->getTagKey($tag), $keys, true)) { + $tagKey = $this->getTagKey($tag); + if (! isset($replacements[$tagKey])) { continue; } + if ($onOverride !== null) { + // phpcs:ignore NeutronStandard.Functions.VariableFunctions.VariableFunction -- Invoke the override observer. + $onOverride((string)$tag, $replacements[$tagKey]); + } + $start = $tag->getAttribute(Attribute::START_INDEX); $end = $tag->getAttribute(Attribute::END_INDEX); assert(is_int($start) && is_int($end)); diff --git a/src/Visitor.php b/src/Visitor.php index 173de43..5855595 100644 --- a/src/Visitor.php +++ b/src/Visitor.php @@ -549,7 +549,14 @@ private function addStringTags(string $name, Doc $docComment): ?Doc return null; } - $newDocComment = (new PhpStanTagMerger())->merge($docComment->getText(), $this->additionalTagStrings[$name]); + $newDocComment = (new PhpStanTagMerger())->merge( + $docComment->getText(), + $this->additionalTagStrings[$name], + static function (string $coreTag, string $mappedTag) use ($name): void { + // phpcs:ignore Generic.PHP.ForbiddenFunctions.Found -- Report intentional overrides during generation. + error_log(sprintf("%s\nCore: %s\nMap: %s", $name, str_replace(["\r", "\n"], ' ', $coreTag), str_replace(["\r", "\n"], ' ', $mappedTag))); + } + ); return new Doc($newDocComment, $docComment->getStartLine(), $docComment->getStartFilePos()); } diff --git a/tests/VisitorTest.php b/tests/VisitorTest.php index 99c32ee..8547ff1 100644 --- a/tests/VisitorTest.php +++ b/tests/VisitorTest.php @@ -91,7 +91,23 @@ function check_admin_referer($action = -1) {} function check_ajax_referer($action = -1, $query_arg = false, $stop = true) {} PHP; - $stubs = self::generateStubs($code); + $logFile = tempnam(sys_get_temp_dir(), 'wpstubs-overrides-'); + self::assertNotFalse($logFile); + // phpcs:ignore Generic.PHP.ForbiddenFunctions.Found,WordPress.PHP.IniSet.Risky -- Capture generator diagnostics in the isolated test. + $previousLog = ini_set('error_log', $logFile); + try { + $stubs = self::generateStubs($code); + $log = file_get_contents($logFile); + self::assertNotFalse($log); + self::assertStringContainsString("check_admin_referer\nCore: @phpstan-param int \$action\nMap: @phpstan-param string \$action", $log); + self::assertStringContainsString("check_admin_referer\nCore: @phpstan-return", $log); + self::assertStringContainsString('Map: @phpstan-return ($action is -1 ? (1 | 2 | false) : (1 | 2))', $log); + self::assertStringNotContainsString('check_ajax_referer', $log); + } finally { + // phpcs:ignore Generic.PHP.ForbiddenFunctions.Found,WordPress.PHP.IniSet.Risky -- Restore the original log destination. + ini_set('error_log', $previousLog === false ? '' : $previousLog); + unlink($logFile); + } self::assertSame(2, substr_count($stubs, '@phpstan-return'), $stubs); self::assertStringContainsString('@phpstan-return ($action is -1 ? 1|2|false : 1|2)', $stubs); From 7b1232ff5765746b73ef77e93ebaf40878464cbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Viktor=20Sz=C3=A9pe?= Date: Sat, 28 Nov 2026 14:11:07 +0000 Subject: [PATCH 07/13] Recommend redundant PHPStan map annotations using structural similarity --- README.md | 26 +++++ phpcs.xml.dist | 1 + phpstan.neon.dist | 1 + recommend-phpstan-tags.php | 58 ++++++++++ src/PhpStanTagSimilarity.php | 168 +++++++++++++++++++++++++++++ src/Visitor.php | 3 +- tests/PhpStanTagSimilarityTest.php | 69 ++++++++++++ tests/VisitorTest.php | 4 +- 8 files changed, 327 insertions(+), 3 deletions(-) create mode 100644 recommend-phpstan-tags.php create mode 100644 src/PhpStanTagSimilarity.php create mode 100644 tests/PhpStanTagSimilarityTest.php diff --git a/README.md b/README.md index 6066098..8490c24 100644 --- a/README.md +++ b/README.md @@ -78,3 +78,29 @@ This package is versioned to match the WordPress version from which the stubs ar 1. And run `./generate.sh` The `wordpress-stubs.php` file should now be updated. + +### Reviewing PHPStan annotation overrides + +Stub generation logs each overridden annotation as three lines: the symbol name, +the original `Core:` tag, and the replacement `Map:` tag. The symbol line also +includes `[similarity: N, recommendation: delete|review]`. Capture STDERR during +generation, then analyze that log without regenerating stubs: + +```sh +./generate.sh 2> overrides.log +php8.5 recommend-phpstan-tags.php overrides.log > recommendations.json +``` + +Each JSON record contains `symbol`, `core`, `map`, `similarity`, `recommendation`, +and `difference`. A similarity of **10** means the parsed annotations are identical +after ignoring descriptions, formatting, global namespace prefixes, and union or +intersection member order. Only these records receive a `delete` recommendation. + +Scores **0–9** estimate structural overlap and always require review. They are not +probabilities, subtype checks, or proof that removing a map entry is safe. The +report shows up to five differing features on each side. Templates include their +name, variance, bound, and default in the identity check. Invalid annotations +receive a score of 0 and require manual review. + +The command only reads the log; it does not modify the map or run generation. +After accepting recommendations, regenerate once and run the full test suite. diff --git a/phpcs.xml.dist b/phpcs.xml.dist index c1f17f9..590dbd4 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -2,6 +2,7 @@ finder.php functionMap.php + recommend-phpstan-tags.php src/ visitor.php tests/ diff --git a/phpstan.neon.dist b/phpstan.neon.dist index ca021d0..431d3b5 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -2,6 +2,7 @@ parameters: paths: - finder.php - functionMap.php + - recommend-phpstan-tags.php - visitor.php - src/ - tests/ diff --git a/recommend-phpstan-tags.php b/recommend-phpstan-tags.php new file mode 100644 index 0000000..57d1749 --- /dev/null +++ b/recommend-phpstan-tags.php @@ -0,0 +1,58 @@ + explode(' [similarity:', $lines[$offset], 2)[0], + 'core' => $coreTag, + 'map' => $mappedTag, + ] + $comparator->compare($coreTag, $mappedTag); +} + +// phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- This CLI runs without WordPress. +echo json_encode($recommendations, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), "\n"; diff --git a/src/PhpStanTagSimilarity.php b/src/PhpStanTagSimilarity.php new file mode 100644 index 0000000..e2d8f33 --- /dev/null +++ b/src/PhpStanTagSimilarity.php @@ -0,0 +1,168 @@ +, recommendation: 'delete'|'review', difference: string} + */ + public function compare(string $coreTag, string $mappedTag): array + { + try { + $core = $this->parse($coreTag); + $mapped = $this->parse($mappedTag); + if ($core->name !== $mapped->name) { + return ['similarity' => 0, 'recommendation' => 'review', 'difference' => 'Different tag kinds.']; + } + + $coreTree = $this->normalizeNode($core->value); + $mappedTree = $this->normalizeNode($mapped->value); + } catch (\InvalidArgumentException | \PHPStan\PhpDocParser\Parser\ParserException $exception) { + return ['similarity' => 0, 'recommendation' => 'review', 'difference' => 'Unsupported or invalid annotation; manual review required.']; + } + + if ($coreTree === $mappedTree) { + return ['similarity' => 10, 'recommendation' => 'delete', 'difference' => 'Identical after PHPDoc normalization.']; + } + + // Matching parameter names or descriptions must not inflate type similarity. + $coreFeatures = $this->features($coreTree['type'] ?? $coreTree); + $mappedFeatures = $this->features($mappedTree['type'] ?? $mappedTree); + $common = array_intersect($coreFeatures, $mappedFeatures); + $total = count($coreFeatures) + count($mappedFeatures); + $similarity = $total === 0 ? 0 : max(0, min(9, (int)round(20 * count($common) / $total))); + $coreDetails = $this->features($coreTree); + $mappedDetails = $this->features($mappedTree); + $coreOnly = array_values(array_diff($coreDetails, $mappedDetails)); + $mappedOnly = array_values(array_diff($mappedDetails, $coreDetails)); + + return [ + 'similarity' => $similarity, + 'recommendation' => 'review', + 'difference' => sprintf( + 'Core only: %s. Map only: %s. Structural similarity does not establish type equivalence or subtyping.', + $coreOnly === [] ? '(none)' : implode('; ', array_slice($coreOnly, 0, 5)), + $mappedOnly === [] ? '(none)' : implode('; ', array_slice($mappedOnly, 0, 5)) + ), + ]; + } + + private function parse(string $tag): PhpDocTagNode + { + $config = new ParserConfig([]); + $constExprParser = new ConstExprParser($config); + $parser = new PhpDocParser($config, new TypeParser($config, $constExprParser), $constExprParser); + $tokens = new TokenIterator((new Lexer($config))->tokenize(sprintf("/**\n * %s\n */", $tag))); + $tags = $parser->parse($tokens)->getTags(); + if (count($tags) !== 1 || ! str_starts_with($tags[0]->name, '@phpstan-')) { + throw new \InvalidArgumentException('Expected one PHPStan annotation.'); + } + + return $tags[0]; + } + + /** @return array */ + private function normalizeNode(Node $node): array + { + if ($node instanceof InvalidTagValueNode || $node instanceof InvalidTypeNode) { + throw new \InvalidArgumentException('Invalid PHPDoc type.'); + } + $properties = []; + foreach (get_object_vars($node) as $property => $child) { + if ($property === 'description') { + continue; + } + $properties[$property] = $this->normalize($child); + } + if ($node instanceof IdentifierTypeNode) { + $properties['name'] = ltrim($node->name, '\\'); + } + if ($node instanceof UnionTypeNode || $node instanceof IntersectionTypeNode) { + $properties['types'] = array_values( + array_map([$this, 'normalizeNode'], $node->types) + ); + $members = []; + foreach ($properties['types'] as $member) { + // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- No WordPress runtime is loaded. + $members[json_encode($member, JSON_THROW_ON_ERROR)] = $member; + } + ksort($members); + $properties['types'] = array_values($members); + } + + return ['node' => $node::class] + $properties; + } + + /** + * @param mixed $node + * @return mixed + */ + // phpcs:ignore NeutronStandard.Functions.TypeHint.NoReturnType -- PHP 7.4 has no mixed return type. + private function normalize($node) + { + if ($node instanceof Node) { + return $this->normalizeNode($node); + } + if (is_array($node)) { + return array_map([$this, 'normalize'], $node); + } + + return $node; + } + + /** + * @param mixed $tree + * @return list + */ + private function features($tree, string $path = ''): array + { + if (! is_array($tree)) { + // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- No WordPress runtime is loaded. + return [sprintf('%s=%s', $path, json_encode($tree, JSON_THROW_ON_ERROR))]; + } + + $features = []; + if (($tree['node'] ?? null) === IdentifierTypeNode::class && isset($tree['name']) && is_string($tree['name'])) { + foreach (['integer' => ['int', 'positive-int', 'negative-int', 'non-negative-int', 'non-positive-int', 'non-zero-int'], 'string' => ['string', 'non-empty-string', 'non-falsy-string', 'numeric-string', 'lowercase-string', 'uppercase-string', 'literal-string']] as $family => $types) { + if (! in_array($tree['name'], $types, true)) { + continue; + } + + $features[] = sprintf('%s.family=%s', $path, $family); + } + } + if (isset($tree['node']) && in_array($tree['node'], [UnionTypeNode::class, IntersectionTypeNode::class], true) && isset($tree['types']) && is_array($tree['types'])) { + $features[] = sprintf('%s.operator=%s', $path, $tree['node']); + foreach ($tree['types'] as $member) { + $features = array_merge($features, $this->features($member, $path)); + } + return array_values(array_unique($features)); + } + foreach ($tree as $property => $child) { + if ($property === 'node') { + continue; + } + $childPath = sprintf('%s.%s', $path, $property); + $features = array_merge($features, $this->features($child, $childPath)); + } + + return array_values(array_unique($features)); + } +} diff --git a/src/Visitor.php b/src/Visitor.php index 5855595..d892239 100644 --- a/src/Visitor.php +++ b/src/Visitor.php @@ -553,8 +553,9 @@ private function addStringTags(string $name, Doc $docComment): ?Doc $docComment->getText(), $this->additionalTagStrings[$name], static function (string $coreTag, string $mappedTag) use ($name): void { + $comparison = (new PhpStanTagSimilarity())->compare($coreTag, $mappedTag); // phpcs:ignore Generic.PHP.ForbiddenFunctions.Found -- Report intentional overrides during generation. - error_log(sprintf("%s\nCore: %s\nMap: %s", $name, str_replace(["\r", "\n"], ' ', $coreTag), str_replace(["\r", "\n"], ' ', $mappedTag))); + error_log(sprintf("%s [similarity: %d, recommendation: %s]\nCore: %s\nMap: %s\n", $name, $comparison['similarity'], $comparison['recommendation'], str_replace(["\r", "\n"], ' ', $coreTag), str_replace(["\r", "\n"], ' ', $mappedTag))); } ); diff --git a/tests/PhpStanTagSimilarityTest.php b/tests/PhpStanTagSimilarityTest.php new file mode 100644 index 0000000..c5e51f0 --- /dev/null +++ b/tests/PhpStanTagSimilarityTest.php @@ -0,0 +1,69 @@ +compare($core, $mapped); + + self::assertSame(10, $result['similarity']); + self::assertSame('delete', $result['recommendation']); + } + + /** @return iterable */ + public function identicalAnnotations(): iterable + { + yield 'template' => ['@phpstan-template T of string = string', '@phpstan-template T of string = string']; + yield 'formatting' => ["@phpstan-return array{\n * id: int,\n * }", '@phpstan-return array{id: int}']; + yield 'union order' => ['@phpstan-return int|string', '@phpstan-return string|int']; + yield 'intersection order' => ['@phpstan-return First&Second', '@phpstan-return Second&First']; + yield 'global namespace' => ['@phpstan-return WP_Post', '@phpstan-return \WP_Post']; + yield 'description' => ['@phpstan-param int $id Existing description.', '@phpstan-param int $id']; + } + + /** @dataProvider differentAnnotations */ + public function testDifferentAnnotationsNeverRecommendDeletion(string $core, string $mapped): void + { + $result = (new PhpStanTagSimilarity())->compare($core, $mapped); + + self::assertGreaterThanOrEqual(0, $result['similarity']); + self::assertLessThanOrEqual(9, $result['similarity']); + self::assertSame('review', $result['recommendation']); + self::assertNotSame('', $result['difference']); + } + + /** @return iterable */ + public function differentAnnotations(): iterable + { + yield 'unrelated' => ['@phpstan-return int', '@phpstan-return string']; + yield 'refinement' => ['@phpstan-return int', '@phpstan-return positive-int']; + yield 'open shape' => ['@phpstan-return array{exit: false}', '@phpstan-return array{exit: false, ...}']; + yield 'optional key' => ['@phpstan-return array{id: int}', '@phpstan-return array{id?: int}']; + yield 'conditional' => ['@phpstan-return ($flag is true ? int : string)', '@phpstan-return ($flag is false ? int : string)']; + yield 'template bound' => ['@phpstan-template T of int', '@phpstan-template T of string']; + yield 'template default' => ['@phpstan-template T of int = int', '@phpstan-template T of int']; + yield 'template variance' => ['@phpstan-template T', '@phpstan-template-covariant T']; + yield 'parameter target' => ['@phpstan-param int $first', '@phpstan-param int $second']; + yield 'invalid identical' => ['@phpstan-return array{', '@phpstan-return array{']; + yield 'multiple tags' => ["@phpstan-return int\n * @phpstan-pure", '@phpstan-return int']; + } + + public function testSmallShapeChangeRanksAboveUnrelatedTypes(): void + { + $comparator = new PhpStanTagSimilarity(); + $smallChange = $comparator->compare('@phpstan-return array{exit: false}', '@phpstan-return array{exit: false, ...}'); + $unrelated = $comparator->compare('@phpstan-return int', '@phpstan-return string'); + + self::assertSame(0, $unrelated['similarity']); + self::assertGreaterThanOrEqual(8, $smallChange['similarity']); + self::assertStringContainsString('sealed', $smallChange['difference']); + } +} diff --git a/tests/VisitorTest.php b/tests/VisitorTest.php index 8547ff1..5ff4425 100644 --- a/tests/VisitorTest.php +++ b/tests/VisitorTest.php @@ -99,8 +99,8 @@ function check_ajax_referer($action = -1, $query_arg = false, $stop = true) {} $stubs = self::generateStubs($code); $log = file_get_contents($logFile); self::assertNotFalse($log); - self::assertStringContainsString("check_admin_referer\nCore: @phpstan-param int \$action\nMap: @phpstan-param string \$action", $log); - self::assertStringContainsString("check_admin_referer\nCore: @phpstan-return", $log); + self::assertStringContainsString("check_admin_referer [similarity: 0, recommendation: review]\nCore: @phpstan-param int \$action\nMap: @phpstan-param string \$action", $log); + self::assertStringContainsString("\nCore: @phpstan-return", $log); self::assertStringContainsString('Map: @phpstan-return ($action is -1 ? (1 | 2 | false) : (1 | 2))', $log); self::assertStringNotContainsString('check_ajax_referer', $log); } finally { From 6bc44b254e09abe18bde335f1a222d4dff461ee9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Viktor=20Sz=C3=A9pe?= Date: Sat, 28 Nov 2026 14:11:13 +0000 Subject: [PATCH 08/13] Use Core PHPStan return annotation for term_exists --- functionMap.php | 1 - tests/data/return/term-exists.php | 29 ----------------------------- wordpress-stubs.php | 13 ++++++++++++- 3 files changed, 12 insertions(+), 31 deletions(-) diff --git a/functionMap.php b/functionMap.php index 4ddf50e..1a0a293 100644 --- a/functionMap.php +++ b/functionMap.php @@ -220,7 +220,6 @@ 'switch_to_blog' => [null, 'deprecated' => 'null'], 'tag_exists' => ["(\$tag_name is 0 ? 0 : (\$tag_name is '' ? null : array{term_id: string, term_taxonomy_id: string}|null))"], 'taxonomy_exists' => ['($taxonomy is non-falsy-string ? bool : false)', '@phpstan-assert-if-true' => '=non-falsy-string $taxonomy'], - 'term_exists' => ["(\$term is 0 ? 0 : (\$term is '' ? null : (\$taxonomy is '' ? string|null : array{term_id: string, term_taxonomy_id: string}|null)))"], 'the_attachment_link' => [null, 'deprecated' => 'false'], 'the_author' => [null, 'deprecated' => "''", 'deprecated_echo' => 'true'], 'the_author_posts_link' => [null, 'deprecated' => "''"], diff --git a/tests/data/return/term-exists.php b/tests/data/return/term-exists.php index a81b3ba..500b30d 100644 --- a/tests/data/return/term-exists.php +++ b/tests/data/return/term-exists.php @@ -12,41 +12,12 @@ $termInt = Faker::int(); $termIntStr = Faker::union(Faker::int(), Faker::string()); -// Empty taxonomy -assertType('string|null', term_exists(123)); -assertType('string|null', term_exists(123, '')); -assertType('string|null', term_exists($termStr)); -assertType('string|null', term_exists($termStr, '')); -assertType('0|string|null', term_exists($termInt)); -assertType('0|string|null', term_exists($termInt, '')); -assertType('0|string|null', term_exists($termIntStr)); -assertType('0|string|null', term_exists($termIntStr, '')); - -// Fixed taxonomy string -assertType('array{term_id: string, term_taxonomy_id: string}|null', term_exists(123, 'category')); -assertType('array{term_id: string, term_taxonomy_id: string}|null', term_exists($termStr, 'category')); -assertType('0|array{term_id: string, term_taxonomy_id: string}|null', term_exists($termInt, 'category')); -assertType('0|array{term_id: string, term_taxonomy_id: string}|null', term_exists($termIntStr, 'category')); - -// Unknown taxonomy type -$taxonomy = (string)$_GET['taxonomy'] ?? ''; -assertType('array{term_id: string, term_taxonomy_id: string}|string|null', term_exists(123, Faker::string())); -assertType('array{term_id: string, term_taxonomy_id: string}|string|null', term_exists($termStr, $taxonomy)); -assertType('0|array{term_id: string, term_taxonomy_id: string}|string|null', term_exists($termInt, Faker::string())); -assertType('0|array{term_id: string, term_taxonomy_id: string}|string|null', term_exists($termIntStr, Faker::string())); - // Term 0 assertType('0', term_exists(0)); assertType('0', term_exists(0, '')); assertType('0', term_exists(0, 'category')); assertType('0', term_exists(0, Faker::string())); -// Term empty string -assertType('null', term_exists('')); -assertType('null', term_exists('', '')); -assertType('null', term_exists('', 'category')); -assertType('null', term_exists('', Faker::string())); - // tag_exists() assertType('0', tag_exists(0)); assertType('null', tag_exists('')); diff --git a/wordpress-stubs.php b/wordpress-stubs.php index f0ce4d7..f73710c 100644 --- a/wordpress-stubs.php +++ b/wordpress-stubs.php @@ -161240,7 +161240,18 @@ function unregister_term_meta($taxonomy, $meta_key) * Returns an array of the term ID and the term taxonomy ID if the taxonomy is specified and the pairing exists. * Returns 0 if term ID 0 is passed to the function. * - * @phpstan-return ($term is 0 ? 0 : ($term is '' ? null : ($taxonomy is '' ? string|null : array{term_id: string, term_taxonomy_id: string}|null))) + * @phpstan-return ( + * $term is null ? null : ( + * $term is 0 ? 0 : ( + * $taxonomy is '' ? int|null : ( + * array{ + * term_id: numeric-string, + * term_taxonomy_id: numeric-string, + * }|null + * ) + * ) + * ) + * ) */ function term_exists($term, $taxonomy = '', $parent_term = \null) { From 5f8503d28d89b92643c49e57c8685f1765f8499f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Viktor=20Sz=C3=A9pe?= Date: Sat, 28 Nov 2026 14:11:17 +0000 Subject: [PATCH 09/13] Add manually triggered monitoring data test suite --- .github/workflows/monitoring-data.yml | 30 +++++++++++++++++++ .../MonitoringParameterTypeTest.php | 29 ++++++++++++++++++ monitoring-tests/MonitoringReturnTypeTest.php | 13 ++++++++ phpunit.monitoring.xml.dist | 16 ++++++++++ 4 files changed, 88 insertions(+) create mode 100644 .github/workflows/monitoring-data.yml create mode 100644 monitoring-tests/MonitoringParameterTypeTest.php create mode 100644 monitoring-tests/MonitoringReturnTypeTest.php create mode 100644 phpunit.monitoring.xml.dist diff --git a/.github/workflows/monitoring-data.yml b/.github/workflows/monitoring-data.yml new file mode 100644 index 0000000..c0faefe --- /dev/null +++ b/.github/workflows/monitoring-data.yml @@ -0,0 +1,30 @@ +name: Monitoring data tests + +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + coverage: none + php-version: "8.5" + + - name: Install dependencies + run: composer install --no-interaction --no-progress --prefer-dist + + - name: Generate stubs + run: ./generate.sh + + - name: Run monitoring data tests + run: vendor/bin/phpunit --configuration=phpunit.monitoring.xml.dist diff --git a/monitoring-tests/MonitoringParameterTypeTest.php b/monitoring-tests/MonitoringParameterTypeTest.php new file mode 100644 index 0000000..3ac5589 --- /dev/null +++ b/monitoring-tests/MonitoringParameterTypeTest.php @@ -0,0 +1,29 @@ +analyse( + __DIR__ . '/../tests/monitoring-data/param/wpdb.php', + [ + [ + "Parameter #2 \$output of method wpdb::get_row() expects 'ARRAY_A'|'ARRAY_N'|'OBJECT', 'OBJECT_K' given.", + 22, + ], + [ + "Parameter #2 \$output of method wpdb::get_row() expects 'ARRAY_A'|'ARRAY_N'|'OBJECT', string given.", + 23, + ], + [ + "Parameter #2 \$output of method wpdb::get_row() expects 'ARRAY_A'|'ARRAY_N'|'OBJECT', int given.", + 24, + ], + ] + ); + } +} diff --git a/monitoring-tests/MonitoringReturnTypeTest.php b/monitoring-tests/MonitoringReturnTypeTest.php new file mode 100644 index 0000000..e28df15 --- /dev/null +++ b/monitoring-tests/MonitoringReturnTypeTest.php @@ -0,0 +1,13 @@ + + + + + ./monitoring-tests/MonitoringParameterTypeTest.php + ./monitoring-tests/MonitoringReturnTypeTest.php + + + From 597bec97dae683da5af226999b9d632773ab1987 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Viktor=20Sz=C3=A9pe?= Date: Sat, 28 Nov 2026 14:13:34 +0000 Subject: [PATCH 10/13] Fix PHP 7.4 compatibility in PHPStan tag similarity --- src/PhpStanTagSimilarity.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/PhpStanTagSimilarity.php b/src/PhpStanTagSimilarity.php index e2d8f33..0f34b20 100644 --- a/src/PhpStanTagSimilarity.php +++ b/src/PhpStanTagSimilarity.php @@ -107,7 +107,8 @@ private function normalizeNode(Node $node): array $properties['types'] = array_values($members); } - return ['node' => $node::class] + $properties; + // phpcs:ignore SlevomatCodingStandard.Classes.ModernClassNameReference.ClassNameReferencedViaFunctionCall -- Dynamic ::class requires PHP 8; support PHP 7.4. + return ['node' => get_class($node)] + $properties; } /** From 507c224b8c7d512e54e757609eac64c30b8522cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Viktor=20Sz=C3=A9pe?= Date: Sat, 28 Nov 2026 14:16:39 +0000 Subject: [PATCH 11/13] Update type assertions for PHPStan 2.3.7 normalization --- tests/data/return/sanitize-post-field.php | 2 +- tests/data/return/zeroise.php | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/data/return/sanitize-post-field.php b/tests/data/return/sanitize-post-field.php index f6f2e7f..85b53ef 100644 --- a/tests/data/return/sanitize-post-field.php +++ b/tests/data/return/sanitize-post-field.php @@ -26,7 +26,7 @@ assertType('array{41, 42, 43}', sanitize_post_field('ancestors', [41, 42, 43], $postId, Faker::string())); assertType('array{foo: 42}', sanitize_post_field('ancestors', ['foo' => 42], $postId, Faker::string())); // And retain list type - regardless of $context -assertType('array, int<0, max>>', sanitize_post_field('ancestors', Faker::list(), $postId, Faker::string())); +assertType('list>', sanitize_post_field('ancestors', Faker::list(), $postId, Faker::string())); // All other constant fields: diff --git a/tests/data/return/zeroise.php b/tests/data/return/zeroise.php index e746778..c3ffa36 100644 --- a/tests/data/return/zeroise.php +++ b/tests/data/return/zeroise.php @@ -8,19 +8,19 @@ use function PHPStan\Testing\assertType; // $threshold is 0 -assertType('lowercase-string&non-empty-string&numeric-string', zeroise(-1, 0)); -assertType('lowercase-string&non-empty-string&numeric-string', zeroise(0, 0)); -assertType('lowercase-string&non-empty-string&numeric-string', zeroise(1, 0)); -assertType('lowercase-string&non-empty-string&numeric-string', zeroise(Faker::int(), 0)); +assertType('lowercase-string&numeric-string', zeroise(-1, 0)); +assertType('lowercase-string&numeric-string', zeroise(0, 0)); +assertType('lowercase-string&numeric-string', zeroise(1, 0)); +assertType('lowercase-string&numeric-string', zeroise(Faker::int(), 0)); // $threshold > 0 assertType('lowercase-string&non-empty-string', zeroise(-1, 5)); -assertType('lowercase-string&non-empty-string&numeric-string', zeroise(0, 5)); -assertType('lowercase-string&non-empty-string&numeric-string', zeroise(1, 5)); +assertType('lowercase-string&numeric-string', zeroise(0, 5)); +assertType('lowercase-string&numeric-string', zeroise(1, 5)); assertType('lowercase-string&non-empty-string', zeroise(Faker::int(), 5)); // $threshold is unknown assertType('lowercase-string&non-empty-string', zeroise(-1, Faker::nonNegativeInt())); -assertType('lowercase-string&non-empty-string&numeric-string', zeroise(0, Faker::nonNegativeInt())); -assertType('lowercase-string&non-empty-string&numeric-string', zeroise(1, Faker::nonNegativeInt())); +assertType('lowercase-string&numeric-string', zeroise(0, Faker::nonNegativeInt())); +assertType('lowercase-string&numeric-string', zeroise(1, Faker::nonNegativeInt())); assertType('lowercase-string&non-empty-string', zeroise(Faker::int(), Faker::nonNegativeInt())); From a52db67e54d3abc63b0bca48abd7955259a1ee40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Viktor=20Sz=C3=A9pe?= Date: Sat, 28 Nov 2026 14:18:52 +0000 Subject: [PATCH 12/13] Support PHPDoc parser NameNode when matching generic tags --- src/PhpStanTagMerger.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PhpStanTagMerger.php b/src/PhpStanTagMerger.php index be8651f..633fa26 100644 --- a/src/PhpStanTagMerger.php +++ b/src/PhpStanTagMerger.php @@ -82,7 +82,7 @@ private function getTagKey(PhpDoc\PhpDocTagNode $tag): string } elseif ($tagValue instanceof PhpDoc\TypeAliasImportTagValueNode) { $target = $tagValue->importedAs ?? $tagValue->importedAlias; } elseif ($tagValue instanceof PhpDoc\ImplementsTagValueNode || $tagValue instanceof PhpDoc\ExtendsTagValueNode || $tagValue instanceof PhpDoc\UsesTagValueNode) { - $target = ltrim($tagValue->type->type->name, '\\'); + $target = ltrim((string)$tagValue->type->type, '\\'); } elseif ($tagValue instanceof PhpDoc\AssertTagValueNode) { $target = $tagValue->parameter; } elseif ($tagValue instanceof PhpDoc\InvalidTagValueNode) { From a0ef81b850c4b8378d7115b9b4c6a16eb5c9946f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Viktor=20Sz=C3=A9pe?= Date: Sat, 28 Nov 2026 14:24:36 +0000 Subject: [PATCH 13/13] Exclude development tooling from release archives --- .gitattributes | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.gitattributes b/.gitattributes index 5908241..f86a86b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,12 +1,18 @@ /.gitattributes export-ignore /.editorconfig export-ignore /.gitignore export-ignore +/.github/ export-ignore +/.typos.toml export-ignore /README.md export-ignore /finder.php export-ignore /functionMap.php export-ignore /generate.sh export-ignore +/monitoring-tests/ export-ignore +/phpcs.xml.dist export-ignore /phpstan.neon.dist export-ignore +/phpunit.monitoring.xml.dist export-ignore /phpunit.xml.dist export-ignore +/recommend-phpstan-tags.php export-ignore /release-latest-versions.sh export-ignore /source/ export-ignore /src/ export-ignore