Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -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
Expand Down
30 changes: 30 additions & 0 deletions .github/workflows/monitoring-data.yml
Original file line number Diff line number Diff line change
@@ -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
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": "*",
Expand Down
3 changes: 1 addition & 2 deletions functionMap.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<min, -1>|'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' => "''"],
Expand Down
29 changes: 29 additions & 0 deletions monitoring-tests/MonitoringParameterTypeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace PhpStubs\WordPress\Core\Tests;

final class MonitoringParameterTypeTest extends IntegrationTest
{
public function testWpdbGetRowOutput(): void
{
$this->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,
],
]
);
}
}
13 changes: 13 additions & 0 deletions monitoring-tests/MonitoringReturnTypeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace PhpStubs\WordPress\Core\Tests;

final class MonitoringReturnTypeTest extends TypeInferenceTest
{
public function getDataDirectory(): string
{
return __DIR__ . '/../tests/monitoring-data/return';
}
}
1 change: 1 addition & 0 deletions phpcs.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<ruleset>
<file>finder.php</file>
<file>functionMap.php</file>
<file>recommend-phpstan-tags.php</file>
<file>src/</file>
<file>visitor.php</file>
<file>tests/</file>
Expand Down
1 change: 1 addition & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ parameters:
paths:
- finder.php
- functionMap.php
- recommend-phpstan-tags.php
- visitor.php
- src/
- tests/
Expand Down
16 changes: 16 additions & 0 deletions phpunit.monitoring.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="tests/bootstrap.php"
colors="true"
failOnRisky="true"
failOnWarning="true"
>
<testsuites>
<testsuite name="monitoring">
<file>./monitoring-tests/MonitoringParameterTypeTest.php</file>
<file>./monitoring-tests/MonitoringReturnTypeTest.php</file>
</testsuite>
</testsuites>
</phpunit>
58 changes: 58 additions & 0 deletions recommend-phpstan-tags.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

declare(strict_types=1);

// phpcs:disable Generic.PHP.ForbiddenFunctions.Found,WordPress.WP.AlternativeFunctions.file_system_operations_fwrite
// Standalone CLI: output, exit codes, and STDERR do not use a WordPress runtime.

use PhpStubs\WordPress\Core\PhpStanTagSimilarity;

require sprintf('%s/vendor/autoload.php', __DIR__);

$arguments = $argv ?? [];
if (count($arguments) !== 2 || $arguments[1] === '--help') {
fwrite(STDERR, "Usage: php8.5 recommend-phpstan-tags.php /path/to/overrides.log\n");
exit(count($arguments) === 2 ? 0 : 1);
}

if (! is_file($arguments[1]) || ! is_readable($arguments[1])) {
fwrite(STDERR, "Cannot read the override log.\n");
exit(1);
}

$lines = file($arguments[1], FILE_IGNORE_NEW_LINES);
if ($lines !== false) {
$lines = array_values(
array_filter(
$lines,
static function (string $line): bool {
return trim($line) !== '';
}
)
);
}
if ($lines === false || count($lines) % 3 !== 0) {
fwrite(STDERR, "Expected three lines per override: symbol, Core tag, Map tag.\n");
exit(1);
}

$comparator = new PhpStanTagSimilarity();
$recommendations = [];
$lineCount = count($lines);
for ($offset = 0; $offset < $lineCount; $offset += 3) {
if (trim($lines[$offset]) === '' || ! str_starts_with($lines[$offset + 1], 'Core: ') || ! str_starts_with($lines[$offset + 2], 'Map: ')) {
fwrite(STDERR, sprintf("Invalid override record starting at line %d.\n", $offset + 1));
exit(1);
}

$coreTag = substr($lines[$offset + 1], 6);
$mappedTag = substr($lines[$offset + 2], 6);
$recommendations[] = [
'symbol' => 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";
95 changes: 95 additions & 0 deletions src/PhpStanTagMerger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<?php

declare(strict_types=1);

namespace PhpStubs\WordPress\Core;

use PHPStan\PhpDocParser\Ast\Attribute;
use PHPStan\PhpDocParser\Ast\PhpDoc;
use PHPStan\PhpDocParser\Lexer\Lexer;
use PHPStan\PhpDocParser\Parser\ConstExprParser;
use PHPStan\PhpDocParser\Parser\PhpDocParser;
use PHPStan\PhpDocParser\Parser\TokenIterator;
use PHPStan\PhpDocParser\Parser\TypeParser;
use PHPStan\PhpDocParser\ParserConfig;

final class PhpStanTagMerger
{
/**
* @param list<string> $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);
}
}
Loading