From 3e97f7dd5a5621eaf1898a8945db5f0e24a54b0b Mon Sep 17 00:00:00 2001 From: "Giuseppe.Esposito" Date: Mon, 16 Nov 2026 10:42:56 +0100 Subject: [PATCH 1/6] Drupal query extend() returns the extender it is given Core declares extend() on a query to return ExtendableInterface, so ->extend(PagerSelectExtender::class)->limit(10) reported limit() as unknown. Make the declaring interface's extend() generic over the class string it takes; the select and extender classes inherit it through {@inheritdoc}. A string that is not a class literal still gives the interface, and a core that changes the declaration keeps its own. Assisted-by: claude-code/claude-opus-5-5 --- src/stub_patches/classes.rs | 12 +- src/stub_patches/drupal.rs | 69 ++++++++++ src/stub_patches/mod.rs | 1 + src/stub_patches/tests.rs | 74 +++++++++++ tests/integration/drupal_return_types.rs | 158 +++++++++++++++++++++++ tests/integration/main.rs | 1 + 6 files changed, 312 insertions(+), 3 deletions(-) create mode 100644 src/stub_patches/drupal.rs create mode 100644 tests/integration/drupal_return_types.rs diff --git a/src/stub_patches/classes.rs b/src/stub_patches/classes.rs index 825b56dc7..36759d677 100644 --- a/src/stub_patches/classes.rs +++ b/src/stub_patches/classes.rs @@ -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() { diff --git a/src/stub_patches/drupal.rs b/src/stub_patches/drupal.rs new file mode 100644 index 000000000..0f295da23 --- /dev/null +++ b/src/stub_patches/drupal.rs @@ -0,0 +1,69 @@ +//! 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. + +use crate::atom::atom; +use crate::php_type::{PhpType, TypeKind}; +use crate::types::ClassInfo; + +use super::classes::{method_index, 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"; + +/// 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), + _ => 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)); + }); +} diff --git a/src/stub_patches/mod.rs b/src/stub_patches/mod.rs index afe8c7b5a..85844c62d 100644 --- a/src/stub_patches/mod.rs +++ b/src/stub_patches/mod.rs @@ -203,6 +203,7 @@ mod active_record; mod classes; +mod drupal; mod functions; mod mockery; diff --git a/src/stub_patches/tests.rs b/src/stub_patches/tests.rs index f94241726..8ad110200 100644 --- a/src/stub_patches/tests.rs +++ b/src/stub_patches/tests.rs @@ -558,3 +558,77 @@ fn tempest_query_patch_leaves_namesakes_and_corrected_annotations_unchanged() { apply_third_party_function_patches(&mut function); assert!(function.parameters.is_empty()); } + +/// Drupal's `ExtendableInterface` with an `extend()` method shaped by +/// `param_name` and `return_type`. +fn extendable_interface(param_name: &str, return_type: &str) -> ClassInfo { + let mut class = empty_class("Drupal\\Core\\Database\\Query\\ExtendableInterface"); + let mut method = crate::types::MethodInfo::virtual_method("extend", Some(return_type)); + method.parameters = vec![param(param_name, "class-string")].into(); + class.methods.make_mut().push(std::sync::Arc::new(method)); + class +} + +#[test] +fn drupal_extend_returns_the_extender_class_it_is_given() { + let mut class = extendable_interface( + "$extender_name", + "Drupal\\Core\\Database\\Query\\ExtendableInterface", + ); + + apply_third_party_class_patches(&mut class); + + let method = &class.methods[0]; + assert_eq!(method.return_type, Some(PhpType::parse("TExtender"))); + assert_eq!( + method.parameters[0].type_hint, + Some(PhpType::parse("class-string")) + ); + assert_eq!(method.template_params(), &[atom("TExtender")]); +} + +#[test] +fn drupal_extend_keeps_a_declaration_core_has_changed() { + for (param_name, return_type) in [ + ( + "$extender_name", + "Drupal\\Core\\Database\\Query\\SelectInterface", + ), + ( + "$class", + "Drupal\\Core\\Database\\Query\\ExtendableInterface", + ), + ] { + let mut class = extendable_interface(param_name, return_type); + + apply_third_party_class_patches(&mut class); + + let method = &class.methods[0]; + assert_eq!(method.return_type, Some(PhpType::parse(return_type))); + assert_eq!( + method.parameters[0].type_hint, + Some(PhpType::parse("class-string")) + ); + assert!(method.template_params().is_empty()); + } +} + +#[test] +fn drupal_extend_keeps_a_parameter_core_no_longer_types_as_a_class_string() { + let mut class = empty_class("Drupal\\Core\\Database\\Query\\ExtendableInterface"); + let mut method = crate::types::MethodInfo::virtual_method( + "extend", + Some("Drupal\\Core\\Database\\Query\\ExtendableInterface"), + ); + method.parameters = vec![param("$extender_name", "string")].into(); + class.methods.make_mut().push(std::sync::Arc::new(method)); + + apply_third_party_class_patches(&mut class); + + let method = &class.methods[0]; + assert_eq!( + method.parameters[0].type_hint, + Some(PhpType::parse("string")) + ); + assert!(method.template_params().is_empty()); +} diff --git a/tests/integration/drupal_return_types.rs b/tests/integration/drupal_return_types.rs new file mode 100644 index 000000000..9f222658d --- /dev/null +++ b/tests/integration/drupal_return_types.rs @@ -0,0 +1,158 @@ +//! Return types Drupal core's docblocks leave wider than the call: the +//! query a select's `extend()` hands back is the extender it is given. + +use crate::common::{completion_response, message_text, response_labels}; +use crate::drupal_services::{position_in, uri_for, workspace_in}; +use tower_lsp_server::gen_lsp_types::*; + +/// Just enough of core's query builder, where Composer would put core. +const QUERY_STUBS: &[(&str, &str)] = &[ + ( + "web/core/lib/Drupal/Core/Database/Query/ExtendableInterface.php", + " String { + format!( + r#" (phpantom_lsp::Backend, tempfile::TempDir, Uri) { + let dir = tempfile::tempdir().unwrap(); + for (path, content) in QUERY_STUBS { + let full = dir.path().join(path); + std::fs::create_dir_all(full.parent().unwrap()).unwrap(); + std::fs::write(full, content).unwrap(); + } + let (backend, dir) = workspace_in(dir, &[(LISTING_PATH, listing)]).await; + backend.ensure_workspace_indexed(); + let uri = uri_for(&dir, LISTING_PATH); + (backend, dir, uri) +} + +/// The messages of the unknown-member warnings in `content`. +fn unknown_members(backend: &phpantom_lsp::Backend, uri: &Uri, content: &str) -> Vec { + let mut diagnostics = Vec::new(); + backend.collect_unknown_member_diagnostics(uri.as_str(), content, &mut diagnostics); + diagnostics + .iter() + .map(|diagnostic| message_text(&diagnostic.message).to_string()) + .collect() +} + +#[tokio::test] +async fn a_select_extended_with_the_pager_has_the_pagers_methods() { + let content = + listing(" $db->select('node', 'n')->extend(PagerSelectExtender::class)->limit(10);"); + let (backend, _dir, uri) = site(&content).await; + + assert_eq!( + unknown_members(&backend, &uri, &content), + Vec::::new() + ); +} + +#[tokio::test] +async fn completion_after_an_extended_select_offers_the_extenders_methods() { + let content = listing( + " $db->select('node', 'n')->extend(PagerSelectExtender::class)->\n ;", + ); + let (backend, _dir, uri) = site(&content).await; + let at = position_in(&content, "::class)->", "::class)->".len()); + + let labels = + response_labels(completion_response(&backend, &uri, at.line, at.character, None).await); + + assert!( + labels.iter().any(|label| label.starts_with("limit")), + "expected limit among {labels:?}" + ); +} + +#[tokio::test] +async fn the_core_select_and_extender_classes_return_the_extender_they_are_given() { + let content = listing( + " $select->extend(PagerSelectExtender::class)->limit(10);\n $extender->extend(PagerSelectExtender::class)->limit(10);", + ); + let (backend, _dir, uri) = site(&content).await; + + assert_eq!( + unknown_members(&backend, &uri, &content), + Vec::::new() + ); +} + +#[tokio::test] +async fn a_chain_of_extenders_ends_with_the_last_one() { + let content = listing( + " $chained = $select->extend(PagerSelectExtender::class)->extend(TableSortExtender::class);\n $chained->orderByHeader([]);\n $chained->limit(10);", + ); + let (backend, _dir, uri) = site(&content).await; + + assert_eq!( + unknown_members(&backend, &uri, &content), + vec![ + "Method Drupal\\Core\\Database\\Query\\TableSortExtender::limit() not found" + .to_string() + ] + ); +} + +#[tokio::test] +async fn an_extender_named_by_a_plain_string_leaves_the_interface() { + let content = listing(" $select->extend($name)->limit(10);"); + let (backend, _dir, uri) = site(&content).await; + + assert_eq!( + unknown_members(&backend, &uri, &content), + vec![ + "Method Drupal\\Core\\Database\\Query\\ExtendableInterface::limit() not found" + .to_string() + ] + ); +} diff --git a/tests/integration/main.rs b/tests/integration/main.rs index 59badc6eb..8494f35c6 100644 --- a/tests/integration/main.rs +++ b/tests/integration/main.rs @@ -232,6 +232,7 @@ mod drupal_mixed_workspace; mod drupal_permissions; mod drupal_plugins; mod drupal_render_elements; +mod drupal_return_types; mod drupal_routes; mod drupal_services; mod drupal_theme_hooks; From be17acb3de5d66ee0f577d524f063f61fc8dbf65 Mon Sep 17 00:00:00 2001 From: "Giuseppe.Esposito" Date: Mon, 16 Nov 2026 10:42:56 +0100 Subject: [PATCH 2/6] Drupal playground: a select query extended with the pager Assisted-by: claude-code/claude-opus-5-5 --- examples/drupal/README.md | 4 ++++ examples/drupal/assertions.php | 10 ++++++++++ .../modules/custom/acme/src/NoteCounter.php | 18 ++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/examples/drupal/README.md b/examples/drupal/README.md index 36da70435..fc73d44d1 100644 --- a/examples/drupal/README.md +++ b/examples/drupal/README.md @@ -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 diff --git a/examples/drupal/assertions.php b/examples/drupal/assertions.php index 56ca15b55..78e84c325 100644 --- a/examples/drupal/assertions.php +++ b/examples/drupal/assertions.php @@ -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; @@ -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()). diff --git a/examples/drupal/web/modules/custom/acme/src/NoteCounter.php b/examples/drupal/web/modules/custom/acme/src/NoteCounter.php index f9efd5a07..84273e74e 100644 --- a/examples/drupal/web/modules/custom/acme/src/NoteCounter.php +++ b/examples/drupal/web/modules/custom/acme/src/NoteCounter.php @@ -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; @@ -68,4 +69,21 @@ public function ids(): array return $ids; } + + /** + * @return array + */ + 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(); + } } From a77db05fbd5ff18907544dd114543f8e4428ce14 Mon Sep 17 00:00:00 2001 From: "Giuseppe.Esposito" Date: Mon, 16 Nov 2026 10:46:52 +0100 Subject: [PATCH 3/6] Drupal URL methods return a string unless asked for metadata Url::toString(), generateFromRoute() and assemble() declare string|GeneratedUrl, but return a GeneratedUrl only when $collect_bubbleable_metadata is TRUE. Key their return type on that flag. Assisted-by: claude-code/claude-opus-5-5 --- src/stub_patches/classes.rs | 2 +- src/stub_patches/drupal.rs | 62 +++++- src/stub_patches/tests.rs | 52 +++++ tests/integration/drupal_return_types.rs | 247 ++++++++++++++++++++++- 4 files changed, 359 insertions(+), 4 deletions(-) diff --git a/src/stub_patches/classes.rs b/src/stub_patches/classes.rs index 36759d677..655a6290f 100644 --- a/src/stub_patches/classes.rs +++ b/src/stub_patches/classes.rs @@ -612,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, diff --git a/src/stub_patches/drupal.rs b/src/stub_patches/drupal.rs index 0f295da23..d965978e9 100644 --- a/src/stub_patches/drupal.rs +++ b/src/stub_patches/drupal.rs @@ -4,23 +4,40 @@ //! 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, update_method_at}; +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 @@ -67,3 +84,46 @@ fn patch_extend(class: &mut ClassInfo) { 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::named(atom("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)) +} diff --git a/src/stub_patches/tests.rs b/src/stub_patches/tests.rs index 8ad110200..7d57e34fd 100644 --- a/src/stub_patches/tests.rs +++ b/src/stub_patches/tests.rs @@ -632,3 +632,55 @@ fn drupal_extend_keeps_a_parameter_core_no_longer_types_as_a_class_string() { ); assert!(method.template_params().is_empty()); } + +/// `Drupal\Core\Url` with a `toString()` returning `return_type` and taking +/// one parameter named `flag`. +fn drupal_url(return_type: Option<&str>, flag: &str) -> ClassInfo { + let mut class = empty_class("Drupal\\Core\\Url"); + let mut method = crate::types::MethodInfo::virtual_method("toString", return_type); + method.parameters = vec![param(flag, "bool")].into(); + class.methods.make_mut().push(std::sync::Arc::new(method)); + class +} + +#[test] +fn drupal_url_methods_return_a_string_unless_asked_for_metadata() { + for declared in [ + Some("string|Drupal\\Core\\GeneratedUrl"), + Some("Drupal\\Core\\GeneratedUrl|string"), + None, + ] { + let mut class = drupal_url(declared, "$collect_bubbleable_metadata"); + + apply_third_party_class_patches(&mut class); + + assert_eq!( + class.methods[0].conditional_return().map(|c| c.to_string()), + Some( + "$collect_bubbleable_metadata is true ? Drupal\\Core\\GeneratedUrl : string" + .to_string() + ), + "{declared:?}" + ); + } +} + +#[test] +fn drupal_url_methods_that_core_already_narrowed_are_left_alone() { + for (declared, flag) in [ + (Some("string"), "$collect_bubbleable_metadata"), + ( + Some("string|Drupal\\Core\\GeneratedUrl"), + "$collect_metadata", + ), + ] { + let mut class = drupal_url(declared, flag); + + apply_third_party_class_patches(&mut class); + + assert!( + class.methods[0].conditional_return().is_none(), + "{declared:?} {flag}" + ); + } +} diff --git a/tests/integration/drupal_return_types.rs b/tests/integration/drupal_return_types.rs index 9f222658d..8656af073 100644 --- a/tests/integration/drupal_return_types.rs +++ b/tests/integration/drupal_return_types.rs @@ -1,7 +1,9 @@ //! Return types Drupal core's docblocks leave wider than the call: the -//! query a select's `extend()` hands back is the extender it is given. +//! query a select's `extend()` hands back is the extender it is given, and +//! a URL is a plain string unless the caller asks for its bubbleable +//! metadata. -use crate::common::{completion_response, message_text, response_labels}; +use crate::common::{completion_response, message_text, response_labels, slow_diagnostic_messages}; use crate::drupal_services::{position_in, uri_for, workspace_in}; use tower_lsp_server::gen_lsp_types::*; @@ -156,3 +158,244 @@ async fn an_extender_named_by_a_plain_string_leaves_the_interface() { ] ); } + +/// Core's URL classes and services as 11.x declares them: the wide return +/// type in the docblock only, and `{@inheritdoc}` on the implementations, +/// followed by prose on the assembler's. +const URL_STUBS: &[(&str, &str)] = &[ + ( + "web/core/lib/Drupal/Core/Render/BubbleableMetadata.php", + "take()`, which wants a +/// `string`. +fn links(body: &str) -> String { + format!( + r#" (phpantom_lsp::Backend, tempfile::TempDir) { + let dir = tempfile::tempdir().unwrap(); + for (path, text) in URL_STUBS { + let full = dir.path().join(path); + std::fs::create_dir_all(full.parent().unwrap()).unwrap(); + std::fs::write(full, text).unwrap(); + } + let (backend, dir) = workspace_in(dir, &[(LINKS_PATH, content)]).await; + // The container is filled from core's YAML by the workspace index. + backend.ensure_workspace_indexed(); + (backend, dir) +} + +/// The `type_mismatch_argument` messages for a consumer running `body`. +async fn argument_mismatches(body: &str) -> Vec { + let content = links(body); + let (backend, dir) = url_site(&content).await; + let uri = uri_for(&dir, LINKS_PATH); + slow_diagnostic_messages(&backend, uri.as_str(), &content, "type_mismatch_argument") +} + +/// The completion labels right after the first `$generated->` in a consumer +/// running `body`. +async fn members_of_generated(body: &str) -> Vec { + let content = links(body); + let (backend, dir) = url_site(&content).await; + let position = position_in(&content, "$generated->", "$generated->".len()); + response_labels( + completion_response( + &backend, + &uri_for(&dir, LINKS_PATH), + position.line, + position.character, + None, + ) + .await, + ) +} + +/// Assert that `found` is the one report of a `GeneratedUrl`, and nothing +/// else, passed where a `string` is expected. +fn assert_exactly_generated_url(found: &[String], context: &str) { + assert_eq!(found.len(), 1, "{context}: {found:?}"); + assert!( + found[0].ends_with("got Drupal\\Core\\GeneratedUrl"), + "{context}: {found:?}" + ); +} + +fn assert_generated_url(labels: &[String]) { + assert!( + labels.iter().any(|l| l.starts_with("getGeneratedUrl")), + "{labels:?}" + ); + assert!( + !labels.iter().any(|l| l.starts_with("getModuleUrl")), + "{labels:?}" + ); +} + +#[tokio::test] +async fn to_string_without_the_flag_is_a_string() { + let found = argument_mismatches(" $this->take($url->toString());").await; + assert!(found.is_empty(), "{found:?}"); +} + +#[tokio::test] +async fn to_string_with_the_flag_off_is_a_string() { + let found = argument_mismatches( + " $this->take($url->toString(FALSE));\n $this->take($url->toString(false));", + ) + .await; + assert!(found.is_empty(), "{found:?}"); +} + +#[tokio::test] +async fn to_string_with_the_flag_on_is_a_generated_url() { + for flag in ["TRUE", "true"] { + let found = + argument_mismatches(&format!(" $this->take($url->toString({flag}));")).await; + assert_exactly_generated_url(&found, flag); + + let labels = members_of_generated(&format!( + " $generated = $url->toString({flag});\n $generated->" + )) + .await; + assert_generated_url(&labels); + } +} + +#[tokio::test] +async fn to_string_with_a_named_flag_is_a_generated_url() { + let found = argument_mismatches( + " $this->take($url->toString(collect_bubbleable_metadata: TRUE));", + ) + .await; + assert_exactly_generated_url(&found, "named"); + + let labels = members_of_generated( + " $generated = $url->toString(collect_bubbleable_metadata: TRUE);\n $generated->", + ) + .await; + assert_generated_url(&labels); +} + +#[tokio::test] +async fn to_string_with_an_unknown_flag_may_be_either() { + let found = argument_mismatches(" $this->take($url->toString($flag));").await; + assert_eq!(found.len(), 1, "{found:?}"); + assert!( + found[0].contains("got Drupal\\Core\\GeneratedUrl|string"), + "{found:?}" + ); +} + +/// Every receiver core hands out for the generator and the assembler, with +/// the call each one makes. +const RECEIVER_CALLS: &[&str] = &[ + "$generator->generateFromRoute('acme.page', [], []", + "$plainGenerator->generateFromRoute('acme.page', [], []", + "$bubblingGenerator->generateFromRoute('acme.page', [], []", + "\\Drupal::service('url_generator')->generateFromRoute('acme.page', [], []", + "\\Drupal::service('url_generator.non_bubbling')->generateFromRoute('acme.page', [], []", + "$assembler->assemble('base:acme', []", + "$plainAssembler->assemble('base:acme', []", + "\\Drupal::service('unrouted_url_assembler')->assemble('base:acme', []", +]; + +#[tokio::test] +async fn every_generator_and_assembler_returns_a_string_without_the_flag() { + for call in RECEIVER_CALLS { + let found = argument_mismatches(&format!(" $this->take({call}));")).await; + assert!(found.is_empty(), "{call}: {found:?}"); + // The receiver resolves: the same call with the flag on is reported. + let found = argument_mismatches(&format!(" $this->take({call}, TRUE));")).await; + assert_eq!(found.len(), 1, "{call}: {found:?}"); + } +} + +#[tokio::test] +async fn every_generator_and_assembler_returns_a_generated_url_with_the_flag() { + for call in RECEIVER_CALLS { + let found = argument_mismatches(&format!(" $this->take({call}, TRUE));")).await; + assert_exactly_generated_url(&found, call); + let labels = members_of_generated(&format!( + " $generated = {call}, TRUE);\n $generated->" + )) + .await; + assert!( + labels.iter().any(|l| l.starts_with("getGeneratedUrl")), + "{call}: {labels:?}" + ); + } +} From 105ae1db43761053e3e6637baa8f5479e92a9988 Mon Sep 17 00:00:00 2001 From: "Giuseppe.Esposito" Date: Mon, 16 Nov 2026 10:46:52 +0100 Subject: [PATCH 4/6] Show URL return types in the Drupal playground Assisted-by: claude-code/claude-opus-5-5 --- examples/drupal/README.md | 6 +++++ examples/drupal/assertions.php | 17 ++++++++++++++ .../web/modules/custom/acme/src/CoreLinks.php | 22 +++++++++++++++++++ 3 files changed, 45 insertions(+) diff --git a/examples/drupal/README.md b/examples/drupal/README.md index fc73d44d1..40499a60f 100644 --- a/examples/drupal/README.md +++ b/examples/drupal/README.md @@ -243,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 diff --git a/examples/drupal/assertions.php b/examples/drupal/assertions.php index 78e84c325..08da4762c 100644 --- a/examples/drupal/assertions.php +++ b/examples/drupal/assertions.php @@ -633,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"; diff --git a/examples/drupal/web/modules/custom/acme/src/CoreLinks.php b/examples/drupal/web/modules/custom/acme/src/CoreLinks.php index e2466269e..7f9879cac 100644 --- a/examples/drupal/web/modules/custom/acme/src/CoreLinks.php +++ b/examples/drupal/web/modules/custom/acme/src/CoreLinks.php @@ -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; + } } From ce70af31fc3d76afa3a0ef75fbfa2d3b5263dc08 Mon Sep 17 00:00:00 2001 From: "Giuseppe.Esposito" Date: Mon, 16 Nov 2026 10:54:59 +0100 Subject: [PATCH 5/6] Changelog and roadmap for Drupal's URL and query return types Assisted-by: claude-code/claude-opus-5-5 --- docs/CHANGELOG.md | 1 + docs/todo.md | 1 - docs/todo/drupal.md | 25 ------------------------- docs/todo/external-stubs.md | 7 ++++++- src/stub_patches/mod.rs | 6 +++++- 5 files changed, 12 insertions(+), 28 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index aed6f80bb..0a23c09d6 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -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 diff --git a/docs/todo.md b/docs/todo.md index 33a44491a..7749c3e07 100644 --- a/docs/todo.md +++ b/docs/todo.md @@ -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 | diff --git a/docs/todo/drupal.md b/docs/todo/drupal.md index f3eaa2b58..4faf71263 100644 --- a/docs/todo/drupal.md +++ b/docs/todo/drupal.md @@ -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** diff --git a/docs/todo/external-stubs.md b/docs/todo/external-stubs.md index 89c47c975..f7fb39f79 100644 --- a/docs/todo/external-stubs.md +++ b/docs/todo/external-stubs.md @@ -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 diff --git a/src/stub_patches/mod.rs b/src/stub_patches/mod.rs index 85844c62d..7fffec04d 100644 --- a/src/stub_patches/mod.rs +++ b/src/stub_patches/mod.rs @@ -147,7 +147,11 @@ //! leave undeclared, the `$args` docblock of Mockery's mock factories, //! whose `array` 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 //! From 38065c6276a2b6ffd29b947efb30024bcf517e2e Mon Sep 17 00:00:00 2001 From: Anders Jenbo Date: Mon, 23 Nov 2026 01:15:26 +0100 Subject: [PATCH 6/6] Use the cached true type in Drupal's URL return correction The conditional return on the URL methods built `true` by hand; PhpType::true_() hands out the interned keyword type instead. Co-Authored-By: Claude Opus 5.5 --- src/stub_patches/drupal.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/stub_patches/drupal.rs b/src/stub_patches/drupal.rs index d965978e9..67582dafb 100644 --- a/src/stub_patches/drupal.rs +++ b/src/stub_patches/drupal.rs @@ -110,7 +110,7 @@ fn patch_url_method(class: &mut ClassInfo, method: &str) { PhpType::conditional( URL_FLAG, false, - PhpType::named(atom("true")), + PhpType::true_(), PhpType::named(atom(GENERATED_URL)), PhpType::string(), ),