Skip to content
Open
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
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
2 changes: 1 addition & 1 deletion functionMap.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<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'],
Expand Down
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($tagValue->type->type->name, '\\');

Check failure on line 85 in src/PhpStanTagMerger.php

View workflow job for this annotation

GitHub Actions / test (8.4)

Access to an undefined property PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode|PHPStan\PhpDocParser\Ast\Type\NameNode::$name.

Check failure on line 85 in src/PhpStanTagMerger.php

View workflow job for this annotation

GitHub Actions / test (8.1)

Access to an undefined property PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode|PHPStan\PhpDocParser\Ast\Type\NameNode::$name.

Check failure on line 85 in src/PhpStanTagMerger.php

View workflow job for this annotation

GitHub Actions / test (8.2)

Access to an undefined property PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode|PHPStan\PhpDocParser\Ast\Type\NameNode::$name.

Check failure on line 85 in src/PhpStanTagMerger.php

View workflow job for this annotation

GitHub Actions / test (8.5)

Access to an undefined property PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode|PHPStan\PhpDocParser\Ast\Type\NameNode::$name.

Check failure on line 85 in src/PhpStanTagMerger.php

View workflow job for this annotation

GitHub Actions / test (8.3)

Access to an undefined property PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode|PHPStan\PhpDocParser\Ast\Type\NameNode::$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);
}
}
14 changes: 7 additions & 7 deletions src/Visitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -549,13 +549,13 @@ 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 {
// 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());
Expand Down
39 changes: 39 additions & 0 deletions tests/PhpStanTagMergerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

namespace PhpStubs\WordPress\Core\Tests;

use PhpStubs\WordPress\Core\PhpStanTagMerger;
use PHPUnit\Framework\TestCase;

final class PhpStanTagMergerTest extends TestCase
{
/**
* @dataProvider tagOverrides
*/
public function testOnlyTheMatchingTagIsReplaced(string $existing, string $replacement, string $unrelated): void
{
$comment = sprintf("/**\n * Description with `@phpstan-return` in prose.\n *\n * @since 1.0\n * %s\n * %s\n */", $existing, $unrelated);
$merged = (new PhpStanTagMerger())->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<string, array{string, string, string}> */
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<int, mixed>', '@phpstan-implements ArrayAccess<int, string>', '@phpstan-implements Iterator<int, mixed>'];
yield 'assertion' => ['@phpstan-assert-if-true int $first', '@phpstan-assert-if-true positive-int $first', '@phpstan-assert-if-true string $second'];
}
}
52 changes: 52 additions & 0 deletions tests/VisitorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,58 @@ function wpstubs_test_connector_with_phpstan_return( string $id ): ?array {
);
}

/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testMapReturnOverridesExistingReturn(): void
{
$code = <<<'PHP'
<?php
/**
* Keep the original description.
*
* @param int|string $action Action to verify.
* @phpstan-param int $action
* @phpstan-return (
* $action is -1 ? int|false : int
* )
*/
function check_admin_referer($action = -1) {}
/**
* @return int|false
*/
function check_ajax_referer($action = -1, $query_arg = false, $stop = true) {}
PHP;

$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);
self::assertStringNotContainsString('@phpstan-param int $action', $stubs);
self::assertSame(2, substr_count($stubs, '@phpstan-param string $action'), $stubs);
self::assertStringContainsString('Keep the original description.', $stubs);
self::assertStringContainsString('Action to verify.', $stubs);
self::assertStringContainsString('@phpstan-param string $action', $stubs);
self::assertStringContainsString('@phpstan-return ($stop is true ? 1|2 : 1|2|false)', $stubs);
}

/**
* Without an existing `@phpstan-return`, the visitor still synthesises one from
* a `@return` tag that uses array hash notation.
Expand Down
Loading
Loading