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 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/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/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..1a0a293 100644 --- a/functionMap.php +++ b/functionMap.php @@ -216,11 +216,10 @@ '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'], - '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/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 @@ + 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/phpunit.monitoring.xml.dist b/phpunit.monitoring.xml.dist new file mode 100644 index 0000000..51e3744 --- /dev/null +++ b/phpunit.monitoring.xml.dist @@ -0,0 +1,16 @@ + + + + + ./monitoring-tests/MonitoringParameterTypeTest.php + ./monitoring-tests/MonitoringReturnTypeTest.php + + + 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/PhpStanTagMerger.php b/src/PhpStanTagMerger.php new file mode 100644 index 0000000..633fa26 --- /dev/null +++ b/src/PhpStanTagMerger.php @@ -0,0 +1,95 @@ + $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); + $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))))); + $replacements = []; + foreach ($mapped->getTags() as $tag) { + $replacements[$this->getTagKey($tag)] = (string)$tag; + } + + $offset = 0; + $parts = []; + $rawTokens = $tokens->getTokens(); + foreach ($original->getTags() as $tag) { + $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)); + 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((string)$tagValue->type->type, '\\'); + } 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/PhpStanTagSimilarity.php b/src/PhpStanTagSimilarity.php new file mode 100644 index 0000000..0f34b20 --- /dev/null +++ b/src/PhpStanTagSimilarity.php @@ -0,0 +1,169 @@ +, 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); + } + + // phpcs:ignore SlevomatCodingStandard.Classes.ModernClassNameReference.ClassNameReferencedViaFunctionCall -- Dynamic ::class requires PHP 8; support PHP 7.4. + return ['node' => get_class($node)] + $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 f15fc5a..d892239 100644 --- a/src/Visitor.php +++ b/src/Visitor.php @@ -549,13 +549,14 @@ private function addStringTags(string $name, Doc $docComment): ?Doc return null; } - $additions = $this->additionalTagStrings[$name]; - - $docCommentText = $docComment->getText(); - $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], + 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 [similarity: %d, recommendation: %s]\nCore: %s\nMap: %s\n", $name, $comparison['similarity'], $comparison['recommendation'], str_replace(["\r", "\n"], ' ', $coreTag), str_replace(["\r", "\n"], ' ', $mappedTag))); + } ); 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/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 a36c7b5..5ff4425 100644 --- a/tests/VisitorTest.php +++ b/tests/VisitorTest.php @@ -67,6 +67,58 @@ function wpstubs_test_connector_with_phpstan_return( string $id ): ?array { ); } + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testMapReturnOverridesExistingReturn(): void + { + $code = <<<'PHP' + 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/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/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())); diff --git a/wordpress-stubs.php b/wordpress-stubs.php index 9565127..f73710c 100644 --- a/wordpress-stubs.php +++ b/wordpress-stubs.php @@ -44993,17 +44993,6 @@ 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()) @@ -50962,9 +50951,6 @@ 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) @@ -107653,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 */ @@ -120906,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))))) */ @@ -130540,9 +130519,6 @@ 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) @@ -132771,14 +132747,6 @@ 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() @@ -132820,14 +132788,6 @@ 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) @@ -133147,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, @@ -150586,7 +150545,6 @@ 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) */ @@ -150608,7 +150566,6 @@ 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) */ @@ -153292,7 +153249,6 @@ 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) */ @@ -153941,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, @@ -154291,11 +154244,6 @@ 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))))) @@ -154792,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, @@ -154845,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, @@ -155364,9 +155306,6 @@ 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) @@ -161313,7 +161252,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) {