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
1 change: 1 addition & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Drupal form and render callbacks.** In a Drupal project, a callback named in a form or render array, such as a `#submit`, `#validate`, `#pre_render`, or `#ajax` callback, jumps to its method or function, completes, shows it on hover, is renamed with it, and lists its references. A callback that names nothing, or that cannot be called, is reported. Contributed by @giuseppe-esposito-87.
- **Drupal event subscribers.** In a Drupal project, event subscribers are read as they are in Symfony: the methods a subscriber's map names navigate and are checked, and an event name passed to the event dispatcher completes and leads to the constant that names it, if any, and to every subscription that listens to it. Contributed by @giuseppe-esposito-87.
- **Drupal entity fields.** In a Drupal project, a content entity's fields are typed properties of the entity and of its interfaces, down to the entity a reference field points to. Field names written in code complete, show their type on hover, and jump to where the field is declared. Contributed by @giuseppe-esposito-87.
- **Precise return types for Drupal's URLs and query extenders.** A URL built without asking for its bubbleable metadata is a plain string, and a query extended with an extender is typed as that extender, so its methods resolve. Contributed by @giuseppe-esposito-87.

#### WordPress

Expand Down
1 change: 0 additions & 1 deletion docs/todo.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,6 @@ ships, remove every row that names it.
| DR18 | [Warn on unknown entity type IDs](todo/drupal.md#dr18-warn-on-unknown-entity-type-ids) | Medium | Low-Medium |
| DR19 | [Warn on unknown hook names](todo/drupal.md#dr19-warn-on-unknown-hook-names) | Low-Medium | Medium |
| DR20 | [Complete route names built in code](todo/drupal.md#dr20-complete-route-names-built-in-code) | Low-Medium | Medium |
| DR21 | [Return types core's docblocks leave wide](todo/drupal.md#dr21-return-types-cores-docblocks-leave-wide) | Medium | Low-Medium |
| DR22 | [Complete permissions built in code](todo/drupal.md#dr22-complete-permissions-built-in-code) | Low-Medium | Medium |
| DR23 | [Warn on unknown permission names](todo/drupal.md#dr23-warn-on-unknown-permission-names) | Medium | Low-Medium |
| DR24 | [Warn on unknown theme hook names](todo/drupal.md#dr24-warn-on-unknown-theme-hook-names) | Low-Medium | Medium-High |
Expand Down
25 changes: 0 additions & 25 deletions docs/todo/drupal.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,31 +164,6 @@ shape.

---

## DR21. Return types core's docblocks leave wide

**Impact: Medium · Complexity: Low-Medium**

```php
$url = Url::fromRoute('acme.greeting')->toString(); // string|GeneratedUrl
$query = $db->select('node', 'n')->extend(PagerSelectExtender::class);
$query->limit(10); // limit() not found on ExtendableInterface
```

A few core methods that Drupal code calls everywhere declare a return
type wider than what the call gives. `Url::toString()` returns a
`GeneratedUrl` only when `$collect_bubbleable_metadata` is `true`, and a
`string` otherwise; PHPStan's Drupal extension ships a stub with the
conditional return type `($collect_bubbleable_metadata is true ?
\Drupal\Core\GeneratedUrl : string)`. `extend()` on a query returns an
instance of the extender class it is given, but declares
`ExtendableInterface`, so every pager or table-sort query loses its
type. Give both the precise type, through the same mechanism as the
other framework corrections ([E7](external-stubs.md#e7-stub-based-framework-patches)
if it has shipped), so a `string` parameter takes the plain
`toString()` and the extender's methods resolve.

---

## DR22. Complete permissions built in code

**Impact: Low-Medium · Complexity: Medium**
Expand Down
7 changes: 6 additions & 1 deletion docs/todo/external-stubs.md
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,12 @@ migration below lets a stub declare only the members it overrides.
no Rust needed).

The phpstorm-stubs patch system (`src/stub_patches/`) is an equally
good candidate for the same treatment once the mechanism exists.
good candidate for the same treatment once the mechanism exists. So
are its third-party corrections, which a stub can express as plain
declarations: Drupal's URL methods (`Url::toString()`,
`generateFromRoute()`, `assemble()`), whose conditional return keys on
`$collect_bubbleable_metadata`, and the method template on a query's
`extend()` (`src/stub_patches/drupal.rs`).

### Scope of the Rust patch system until then

Expand Down
10 changes: 10 additions & 0 deletions examples/drupal/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ Run `composer install` here first. Composer puts core and contrib into
`'field_tags'`, which lands in its field storage file, hover it for its
field type, or find its references, the `$note->field_tags` reads
included; `$tags`, from `get('field_tags')`, is typed as the field is.
- A database query's `extend()` returns the extender it is given. In
`firstPageIds()` in `web/modules/custom/acme/src/NoteCounter.php`,
complete after `->extend(PagerSelectExtender::class)->`: the pager's
`limit()` is offered, and is no unknown method.
- Route names navigate between the routing file that declares them and the
code, links files, and templates that name them. In
`web/modules/custom/acme/src/Controller/GreetingController.php`, go to the
Expand Down Expand Up @@ -239,6 +243,12 @@ Run `composer install` here first. Composer puts core and contrib into
the subscription, and the dispatch are one list. Complete an event name
inside the quotes of `dispatch()` or of the dispatcher's other methods
that take one.
- A URL is a string unless the call asks for its bubbleable metadata. In
`firstNodePath()` in `web/modules/custom/acme/src/CoreLinks.php`, a plain
`toString()` passed to a `string` parameter is not reported, and
`toString(TRUE)` is a `GeneratedUrl` that completes `getGeneratedUrl()`.
The URL generator's `generateFromRoute()` and the assembler's
`assemble()` follow the same flag.

## What the Symfony support already reads

Expand Down
27 changes: 27 additions & 0 deletions examples/drupal/assertions.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@
use Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldConstraint;
use Drupal\Core\Config\ConfigBase;
use Drupal\Core\Config\FileStorage;
use Drupal\Core\Database\Query\ExtendableInterface;
use Drupal\Core\Database\Query\PagerSelectExtender;
use Drupal\Core\Database\Query\Select;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ClassResolver;
use Drupal\Core\DependencyInjection\ContainerBuilder;
Expand Down Expand Up @@ -387,6 +390,13 @@ function listenerMethods(array $events): array
check('NoteSummary::isTagged() asks for and reads field_tags by name', str_contains($summarySource, "\$note->hasField('field_tags')") && str_contains($summarySource, "\$tags = \$note->get('field_tags');"));
check('NoteSummary::isTagged() returns a bool', (new ReflectionMethod(NoteSummary::class, 'isTagged'))->getReturnType()?->getName() === 'bool');

// A query's extend() builds the extender class it is given, which PHPantom
// reads from the parameter extend() declares.
check("ExtendableInterface::extend() takes the extender's class as \$extender_name", (new ReflectionMethod(ExtendableInterface::class, 'extend'))->getParameters()[0]->getName() === 'extender_name');
check('the select query Connection::select() builds is extendable', is_subclass_of(Select::class, ExtendableInterface::class));
check('PagerSelectExtender is extendable and has limit()', is_subclass_of(PagerSelectExtender::class, ExtendableInterface::class) && (new ReflectionClass(PagerSelectExtender::class))->hasMethod('limit'));
check('NoteCounter::firstPageIds() extends its query with PagerSelectExtender and limits it', str_contains((string) file_get_contents("$module/src/NoteCounter.php"), "->extend(PagerSelectExtender::class)\n ->limit(10);"));

// Drupal upcasts a controller's parameter named after an entity type and
// hinted with a class or interface the entity class is (core's
// EntityResolverManager::setParametersFromReflection()).
Expand Down Expand Up @@ -623,6 +633,23 @@ function listenerMethods(array $events): array
check('acme.services.yml builds acme.greeter from Greeter, which declares buildGreeting()', $container->getDefinition('acme.greeter')->getClass() === Greeter::class && (new ReflectionMethod(Greeter::class, 'buildGreeting'))->isPublic());
check('Greeter trusts buildGreeting() as a render callback', is_subclass_of(Greeter::class, TrustedCallbackInterface::class) && in_array('buildGreeting', Greeter::trustedCallbacks(), true));

// The URL methods return a GeneratedUrl only when asked for its bubbleable
// metadata, through a flag that defaults to FALSE. PHPantom keys their
// return type on that parameter's name.
foreach ([
[\Drupal\Core\Url::class, 'toString'],
[\Drupal\Core\Routing\UrlGeneratorInterface::class, 'generateFromRoute'],
[\Drupal\Core\Utility\UnroutedUrlAssemblerInterface::class, 'assemble'],
] as [$urlClass, $urlMethod]) {
$urlFlag = array_values(array_filter(
(new ReflectionMethod($urlClass, $urlMethod))->getParameters(),
static fn (ReflectionParameter $parameter): bool => $parameter->getName() === 'collect_bubbleable_metadata',
))[0] ?? null;
check("$urlClass::$urlMethod() takes \$collect_bubbleable_metadata, FALSE by default", $urlFlag !== null && $urlFlag->isDefaultValueAvailable() && $urlFlag->getDefaultValue() === false);
}
check('A GeneratedUrl has getGeneratedUrl()', method_exists(\Drupal\Core\GeneratedUrl::class, 'getGeneratedUrl'));
check('CoreLinks::firstNodePath() passes a plain toString() to a string parameter and uses toString(TRUE) as a GeneratedUrl', str_contains((string) file_get_contents("$module/src/CoreLinks.php"), '$this->describe($url->toString())') && str_contains((string) file_get_contents("$module/src/CoreLinks.php"), '$url->toString(TRUE)'));

// ─── Summary ────────────────────────────────────────────────────────────────

echo "\n";
Expand Down
22 changes: 22 additions & 0 deletions examples/drupal/web/modules/custom/acme/src/CoreLinks.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,26 @@ public function urls(): array
Url::fromRoute('view.content.page_1'),
];
}

/**
* The path of the first node, told plainly and with its cacheability.
*/
public function firstNodePath(): string
{
$url = Url::fromRoute('entity.node.canonical', ['node' => 1]);

// Try: core declares toString() string|GeneratedUrl, but without
// TRUE it returns a plain string, so passing it to describe() is not
// reported. With TRUE it returns a GeneratedUrl: complete after
// `$generated->` to reach getGeneratedUrl().
$plain = $this->describe($url->toString());
$generated = $url->toString(TRUE);

return $plain . ' ' . $generated->getGeneratedUrl();
}

private function describe(string $path): string
{
return 'Path: ' . $path;
}
}
18 changes: 18 additions & 0 deletions examples/drupal/web/modules/custom/acme/src/NoteCounter.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Drupal\acme;

use Drupal\acme\Entity\Note;
use Drupal\Core\Database\Query\PagerSelectExtender;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
Expand Down Expand Up @@ -68,4 +69,21 @@ public function ids(): array

return $ids;
}

/**
* @return array<int, string>
*/
public function firstPageIds(): array
{
// Try: complete after `->extend(PagerSelectExtender::class)->`. A
// query's extend() returns the extender it is given, so the pager's
// `limit()` is no unknown method.
$query = \Drupal::database()
->select('acme_note', 'n')
->extend(PagerSelectExtender::class)
->limit(10);
$query->fields('n', ['id']);

return $query->execute()->fetchCol();
}
}
14 changes: 10 additions & 4 deletions src/stub_patches/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,16 +128,22 @@ const THIRD_PARTY_ASSERT_IF_TRUE: &[(&str, &str, &str)] = &[(
"$this->getClassReflection()",
)];

/// Supply the `@phpstan-assert-if-true` tags that [`THIRD_PARTY_ASSERT_IF_TRUE`]
/// records, for a class parsed from the user's project or its vendor tree.
/// Apply the corrections for third-party classes to a class parsed from
/// the user's project or its vendor tree: `yiisoft/active-record`'s query
/// generics, Mockery's mock arguments, Drupal core's return types, and the
/// `@phpstan-assert-if-true` tags that [`THIRD_PARTY_ASSERT_IF_TRUE`]
/// records.
///
/// Separate from [`apply_class_stub_patches`], which is deliberately
/// confined to the embedded stubs: this one has to reach vendor code, so
/// it does nothing at all for a class whose FQN is not in the list.
/// it does nothing at all for a class whose FQN none of them names.
pub fn apply_third_party_class_patches(class: &mut ClassInfo) {
if super::active_record::patch(class) {
return;
}
if super::drupal::patch(class) {
return;
}
let fqn = class.fqn();
if let Some(methods) = super::mockery::mock_methods_of(fqn.as_str()) {
for idx in 0..class.methods.len() {
Expand Down Expand Up @@ -606,7 +612,7 @@ fn patch_reflection_object(class: &mut ClassInfo) {

/// Give a method a conditional return type, provided the stub declares the
/// parameter the conditional keys on.
fn patch_method_conditional_return(
pub(super) fn patch_method_conditional_return(
class: &mut ClassInfo,
method_name: &str,
param_name: &str,
Expand Down
129 changes: 129 additions & 0 deletions src/stub_patches/drupal.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
//! Return types Drupal core's docblocks leave wider than the call.
//!
//! A query's `extend()` is declared to return `ExtendableInterface`, but it
//! builds the extender class it is given, so
//! `->extend(PagerSelectExtender::class)->limit(10)` forgets the pager's
//! methods. The method becomes generic over that class.
//!
//! Core declares `string|GeneratedUrl` on the URL methods that take
//! `$collect_bubbleable_metadata`, but the flag decides: they return a
//! plain string unless it is `TRUE`.
//!
//! Each correction is keyed on the exact FQN, and leaves alone a
//! declaration that no longer looks the way it is corrected for.

use crate::atom::atom;
use crate::php_type::{PhpType, TypeKind};
use crate::types::ClassInfo;

use super::classes::{method_index, patch_method_conditional_return, update_method_at};

const EXTENDABLE_INTERFACE: &str = "Drupal\\Core\\Database\\Query\\ExtendableInterface";

/// The template `extend()` binds from the extender class it is given.
const EXTENDER: &str = "TExtender";

const GENERATED_URL: &str = "Drupal\\Core\\GeneratedUrl";
const URL_FLAG: &str = "$collect_bubbleable_metadata";

/// Correct the return types of Drupal core's classes; `false` for any
/// other class.
pub(super) fn patch(class: &mut ClassInfo) -> bool {
match class.fqn().as_str() {
EXTENDABLE_INTERFACE => patch_extend(class),
"Drupal\\Core\\Url" => patch_url_method(class, "toString"),
"Drupal\\Core\\Routing\\UrlGeneratorInterface" => {
patch_url_method(class, "generateFromRoute")
}
"Drupal\\Core\\Utility\\UnroutedUrlAssemblerInterface" => {
patch_url_method(class, "assemble")
}
_ => return false,
}
true
}

/// `extend(PagerSelectExtender::class)` returns a `PagerSelectExtender`.
///
/// Left alone when the method no longer takes `$extender_name` as a plain
/// `class-string`, already declares templates, or declares a return type
/// other than the interface.
fn patch_extend(class: &mut ClassInfo) {
let Some(idx) = method_index(class, "extend") else {
return;
};
let method = &class.methods[idx];
let Some(first) = method.parameters.first() else {
return;
};
let param = first.name;
if param != "$extender_name"
|| first
.type_hint
.as_ref()
.is_some_and(|ty| !matches!(ty.kind(), TypeKind::ClassString(None)))
|| !method.template_params().is_empty()
|| method
.return_type
.as_ref()
.is_some_and(|ty| !ty.is_named(EXTENDABLE_INTERFACE))
{
return;
}
let template = atom(EXTENDER);
update_method_at(class, idx, |method| {
if let Some(first) = method.parameters.make_mut().first_mut() {
first.type_hint = Some(PhpType::class_string(Some(PhpType::named(template))));
}
method.return_type = Some(PhpType::named(template));
let extras = method.extras_mut();
extras.template_params.push(template);
extras
.template_param_bounds
.insert(template, PhpType::named(atom(EXTENDABLE_INTERFACE)));
extras.template_bindings.push((template, param));
});
}

/// `$method` returns a `GeneratedUrl` when the flag is `TRUE`, and a plain
/// string otherwise.
///
/// Left alone when the method no longer takes the flag, already declares a
/// conditional return, or declares a return type other than the union.
fn patch_url_method(class: &mut ClassInfo, method: &str) {
let Some(idx) = method_index(class, method) else {
return;
};
let declared = &class.methods[idx];
if declared.conditional_return().is_some()
|| !declared
.return_type
.as_ref()
.is_none_or(is_string_or_generated_url)
{
return;
}
patch_method_conditional_return(
class,
method,
URL_FLAG,
PhpType::conditional(
URL_FLAG,
false,
PhpType::true_(),
PhpType::named(atom(GENERATED_URL)),
PhpType::string(),
),
);
}

/// Whether `ty` is the `string|GeneratedUrl` core declares, its class name
/// stored resolved.
fn is_string_or_generated_url(ty: &PhpType) -> bool {
let TypeKind::Union(members) = ty.kind() else {
return false;
};
members.len() == 2
&& members.iter().any(|m| m.is_string_type())
&& members.iter().any(|m| m.is_named(GENERATED_URL))
}
7 changes: 6 additions & 1 deletion src/stub_patches/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,11 @@
//! leave undeclared, the `$args` docblock of Mockery's mock factories,
//! whose `array<TMock>` alternative is really constructor arguments, the
//! record class a `yiisoft/active-record` query is for (see
//! `active_record.rs`), and the model class accepted by Tempest's `query()`.
//! `active_record.rs`), the model class accepted by Tempest's `query()`,
//! and the return types Drupal core declares wider than the call (see
//! `drupal.rs`): the URL methods that return a plain string unless asked
//! for bubbleable metadata, and a query's `extend()`, which returns the
//! extender it is given.
//!
//! ### Class patches
//!
Expand Down Expand Up @@ -203,6 +207,7 @@

mod active_record;
mod classes;
mod drupal;
mod functions;
mod mockery;

Expand Down
Loading
Loading