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
18 changes: 18 additions & 0 deletions benches/drupal_completion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,12 @@ final class Consumer
$this->blocks->createInstance('mod1_');
$themed = ['#theme' => 'mod1_'];
$build = ['#attached' => ['library' => ['mod1/']]];
$build = ['#submit' => ['mod1_']];
$build = ['#pre_render' => ['Drupal\acme\Consumer::r']];
}
}

function mod1_submit(): void {}
"#;

const MODULE_PATH: &str = "web/modules/custom/acme/acme.module";
Expand Down Expand Up @@ -445,6 +449,20 @@ fn bench_drupal_name_completion(c: &mut Criterion) {
"['library' => ['mod1/'",
"mod1/library7",
),
(
"callback_function",
&consumer,
CONSUMER_PHP,
"['#submit' => ['mod1_'",
"Drupal\\acme\\mod1_submit",
),
(
"callback_method",
&consumer,
CONSUMER_PHP,
"['#pre_render' => ['Drupal\\acme\\Consumer::r'",
"run",
),
(
"hook_implementation",
&module,
Expand Down
1 change: 1 addition & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Unknown Drupal services.** In a Drupal project, a service ID that `\Drupal::service()` or a container's `get()` looks up is reported when no services file declares it and no service provider, compiler pass, or other PHP code could define it. A lookup the code checks with `has()` first, one that runs only when `moduleExists()` finds a module the site lacks, or one in a file that may catch the exception a missing service throws, is left alone, and so is test code.
- **Drupal annotations without imports.** In a Drupal project, an annotation on a plugin class that no `use` imports, such as `@Block` or `@Translation`, jumps to its class, shows it on hover, and is found by Find References, wherever Drupal's plugin discovery would find it.
- **Controller methods of a Drupal service.** In a routing file, the method of a `_controller` or `_title_callback` written as `service:method` jumps to the method of the service's class, completes from its public methods, and is listed among the method's references.
- **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.

#### WordPress

Expand Down
1 change: 1 addition & 0 deletions docs/diagnostics.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ These are shown dimmed rather than underlined, except `unwritten_property`.
| `invalid_drupal_service` | Warning | A service ID no services file declares and no PHP code may define. |
| `invalid_drupal_plugin` | Warning | A plugin ID no plugin of its type declares and no PHP code may add. |
| `invalid_drupal_render_element` | Warning | A render element `#type` no element class declares. |
| `invalid_drupal_callback` | Warning | A form or render callback Drupal cannot call: `'::method'` in a render callback, an array callable that names a non-static method by its class, or a value callback that is not a native callable. |

## External tools

Expand Down
6 changes: 5 additions & 1 deletion docs/todo.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,6 @@ ships, remove every row that names it.
| # | Item | Impact | Complexity |
| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | ----------- |
| F59 | [Send Twig, YAML, and XML documents to the server from Zed](todo/lsp-features.md#f59-send-twig-yaml-and-xml-documents-to-the-server-from-zed) (Zed PR) | Medium | Low |
| DR11 | [Form and render callbacks](todo/drupal.md#dr11-form-and-render-callbacks) | Low-Medium | Low-Medium |
| DR12 | [Translation placeholders](todo/drupal.md#dr12-translation-placeholders) | Low-Medium | Low-Medium |
| DR13 | [Module names and `*.info.yml`](todo/drupal.md#dr13-module-names-and-infoyml) | Low-Medium | Low-Medium |
| DR14 | [Port PHPStan's Drupal extension tests](todo/drupal.md#dr14-port-phpstans-drupal-extension-tests) | Medium | Medium |
Expand All @@ -145,6 +144,11 @@ ships, remove every row that names it.
| DR24 | [Warn on unknown theme hook names](todo/drupal.md#dr24-warn-on-unknown-theme-hook-names) | Low-Medium | Medium-High |
| DR28 | [Plugin types a manager builds at run time](todo/drupal.md#dr28-plugin-types-a-manager-builds-at-run-time) | Medium | Medium |
| DR27 | [Plugin IDs in YAML](todo/drupal.md#dr27-plugin-ids-in-yaml) | Low-Medium | Medium |
| DR32 | [`'::method'` callbacks in a form alter hook](todo/drupal.md#dr32-method-callbacks-in-a-form-alter-hook) | Low-Medium | Low-Medium |
| DR33 | [Render callbacks that are not trusted](todo/drupal.md#dr33-render-callbacks-that-are-not-trusted) | Low-Medium | Low |
| DR34 | [Callback parameter checks](todo/drupal.md#dr34-callback-parameter-checks) | Low | Low-Medium |
| DR35 | [Invokable classes and services as callbacks](todo/drupal.md#dr35-invokable-classes-and-services-as-callbacks) | Low | Low-Medium |
| DR36 | [Array callables that name their class in a string](todo/drupal.md#dr36-array-callables-that-name-their-class-in-a-string) | Low | Low |

## Yii

Expand Down
99 changes: 81 additions & 18 deletions docs/todo/drupal.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ the plugins of each, the permissions the `*.permissions.yml`
files declare, the configuration objects and keys the default
configuration and the configuration schema declare, the theme hooks
`hook_theme()` implementations declare, the render elements element
classes declare, and the libraries the `*.libraries.yml` files declare
are read. Nothing reads fields yet.
classes declare, the libraries the `*.libraries.yml` files declare, and
the callbacks form and render arrays name are read. Nothing reads fields yet.

The requests in
[#48](https://github.com/PHPantom-dev/phpantom_lsp/issues/48) are the
Expand Down Expand Up @@ -70,22 +70,6 @@ names and report a misspelt one.

---

## DR11. Form and render callbacks

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

```php
$form['actions']['submit']['#submit'][] = '::submitOrder';
$form['country']['#ajax'] = ['callback' => '::updateRegions'];
```

`#submit`, `#validate`, `#element_validate`, `#pre_render`,
`#after_build`, and an `#ajax` `callback` name methods of the form class
as `'::method'`, or a function or `Class::method`. Navigate, rename, and
complete them, and report one that names nothing.

---

## DR12. Translation placeholders

**Impact: Low-Medium · Complexity: Low-Medium**
Expand Down Expand Up @@ -365,3 +349,82 @@ argument, which each service in `views.services.yml` and
sources and processes) neither complete nor navigate. Read the argument
each such service passes, and type the service by the plugin type it
builds.

---

## DR32. `'::method'` callbacks in a form alter hook

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

```php
function acme_form_node_article_form_alter(array &$form, FormStateInterface $form_state) {
$form['actions']['submit']['#submit'][] = '::saveDraft';
}
```

In `hook_form_FORM_ID_alter()`, or `#[Hook('form_FORM_ID_alter')]`, a
`'::method'` names a method of the form class that `FORM_ID` belongs to,
not of the module's own class. Resolve the form ID to its form class, so
the callback navigates, completes, renames, and is reported when the
class has no such method.

---

## DR33. Render callbacks that are not trusted

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

```php
$build['#pre_render'][] = [Formatter::class, 'prepare'];
```

Drupal refuses to run a `#pre_render`, `#post_render`, `#lazy_builder`, or
`#access_callback` callback that is not trusted. Report a callback whose
class implements neither `TrustedCallbackInterface` nor
`RenderCallbackInterface`, and one whose method `trustedCallbacks()` does
not list.

---

## DR34. Callback parameter checks

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

```php
public function submitOrder(array $form) {}
```

A submit or validate handler takes `array &$form, FormStateInterface
$form_state`, and an `#ajax` callback takes the same two parameters.
Report a callback that takes a different list, such as one that lacks the
form state or types it as something else.

---

## DR35. Invokable classes and services as callbacks

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

```php
$form['#validate'][] = [OrderValidator::class, '__invoke'];
$form['#submit'][] = 'order_handler:submit';
```

A class with `__invoke()` named as a callback, and a class name written
as the service part of `'Class:method'`, are not read as callbacks.
Navigate, rename, and report them like any other callback.

---

## DR36. Array callables that name their class in a string

**Impact: Low · Complexity: Low**

```php
$form['#submit'][] = ['Drupal\acme\Form\OrderForm', 'submitOrder'];
```

An array callable whose class is a string rather than `OrderForm::class`
names no method, so it neither navigates nor renames, and a method the
class lacks is not reported. Read the string as the fully qualified class
name PHP reads it as, wherever an array callable is read.
20 changes: 20 additions & 0 deletions examples/drupal/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,26 @@ Run `composer install` here first. Composer puts core and contrib into
`Details` class. Complete a name inside `'#type' => ''` or
`$build['more']['#type'] = ''`; core's elements are offered too. A name
no element class declares is reported.
- Form and render callbacks navigate to the method or function they name.
In `web/modules/custom/acme/src/Form/GreetingForm.php`, go to the
definition of `validateName` in `'::validateName'`, which lands on the
form's own method, hover `trimName` in `static::class . '::trimName'`, or
go to the definition of `addHint` in
`'Drupal\acme\Form\GreetingForm::addHint'` and of
`'acme_greeting_form_submit'`, a function of `acme.module`. Find the
references of a callback method, or rename it, and the strings follow.
Complete inside a callback string: after `'::` the form's public methods
are offered, after `'Class::` the class's, after `'service:` the service
class's, and before any colon the functions. A callback Drupal cannot
call is reported: misspell `'::validateName'`, make `validateName`
private, or make `trimName` non-static, which Drupal ignores as a value
callback.
A `'service:method'` callback leads to the method of the service's
class: in `card()` in
`web/modules/custom/acme/src/Controller/GreetingController.php`, go to
the definition of `buildGreeting` in `'acme.greeter:buildGreeting'`,
which lands on Greeter's method, or of `acme.greeter`, which lands on
its key in `acme.services.yml`.
- Plugin IDs navigate to the plugin class that declares them, for every
plugin type a plugin manager declares, core's and contributed modules'
included. In `block()` in
Expand Down
49 changes: 49 additions & 0 deletions examples/drupal/assertions.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Drupal\acme\Controller\NoteController;
use Drupal\acme\Element\GreetingCard;
use Drupal\acme\Entity\Note;
use Drupal\acme\Form\GreetingForm;
use Drupal\acme\Form\SettingsForm;
use Drupal\acme\Greeter;
use Drupal\acme\Hook\AcmeHooks;
Expand All @@ -40,6 +41,7 @@
use Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldConstraint;
use Drupal\Core\Config\ConfigBase;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ClassResolver;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\DependencyInjection\YamlFileLoader;
Expand All @@ -53,8 +55,11 @@
use Drupal\Core\Extension\InfoParser;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\ConfigTarget;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Hook\Attribute\Hook;
use Drupal\Core\Language\LanguageManager;
use Drupal\Core\Security\TrustedCallbackInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Link;
Expand All @@ -64,6 +69,7 @@
use Drupal\Core\Render\Element\Details;
use Drupal\Core\Render\Element\RenderElementBase;
use Drupal\Core\Url;
use Drupal\Core\Utility\CallableResolver;
use Drupal\language\ConfigurableLanguageManager;
use Drupal\language\LanguageServiceProvider;

Expand Down Expand Up @@ -433,6 +439,49 @@ protected function getDefaultLanguageValues()
check("core's Twig extension declares attach_library()", str_contains((string) file_get_contents("$web/core/lib/Drupal/Core/Template/TwigExtension.php"), "new TwigFunction('attach_library'"));
check("core's ThemeManager collects the #attached a preprocess function sets", str_contains((string) file_get_contents("$web/core/lib/Drupal/Core/Theme/ThemeManager.php"), "foreach (['#attached', '#cache'] as \$key)"));

// ─── Callbacks ──────────────────────────────────────────────────────────────

// Drupal rewrites a '::method' callback as a call on the form object, and
// calls every other one as written. Each one GreetingForm declares names a
// public method or function, so each one is callable.
$greetingForm = new GreetingForm();
$greetingFormState = (new FormState())->setFormObject($greetingForm);
$greetingBuild = $greetingForm->buildForm([], $greetingFormState);
$greetingCallbacks = [
...$greetingBuild['#validate'],
$greetingBuild['name']['#value_callback'],
$greetingBuild['name']['#ajax']['callback'],
...$greetingBuild['#after_build'],
...$greetingBuild['actions']['submit']['#submit'],
];
check('GreetingForm declares a callback of each shape', $greetingCallbacks === ['::validateName', GreetingForm::class . '::trimName', '::refreshGreeting', 'Drupal\acme\Form\GreetingForm::addHint', '::submitForm', 'acme_greeting_form_submit']);
foreach ($greetingCallbacks as $callback) {
check("Drupal can call GreetingForm's $callback", is_callable($greetingFormState->prepareCallback($callback)));
}
check("FormState rewrites '::validateName' as a call on the form object", $greetingFormState->prepareCallback('::validateName') === [$greetingForm, 'validateName']);
// A value callback must be a native callable: a static method named by its
// class is one, and an instance method named by its class or '::method' is
// not.
check('the value callback trimName is a native callable', is_callable(GreetingForm::class . '::trimName'));
check('an instance method named by its class is no native callable', !is_callable(GreetingForm::class . '::validateName'));
check("'::trimName' is no native callable", !is_callable('::trimName'));
// Drupal calls a callback from outside the form, where only a public
// method is callable.
check('validateName is public', (new ReflectionMethod(GreetingForm::class, 'validateName'))->isPublic());
check('a private method is not callable from outside its class', !is_callable([new class { public function run(): void { $this->hidden(); } private function hidden(): void {} }, 'hidden']));
check('GreetingForm is a form', $greetingForm instanceof FormInterface);

// The card's lazy builder names a method of the acme.greeter service, which
// Drupal's CallableResolver finds through the container. A lazy builder
// must be a trusted callback.
check("GreetingController::card() has the lazy builder 'acme.greeter:buildGreeting'", str_contains((string) file_get_contents("$module/src/Controller/GreetingController.php"), "'#lazy_builder' => ['acme.greeter:buildGreeting', [\$name]]"));
$lazyContainer = new ContainerBuilder();
$lazyContainer->set('acme.greeter', (new ReflectionClass(Greeter::class))->newInstanceWithoutConstructor());
$lazyCallable = (new CallableResolver(new ClassResolver($lazyContainer)))->getCallableFromDefinition('acme.greeter:buildGreeting');
check("CallableResolver calls 'acme.greeter:buildGreeting' on the service", is_array($lazyCallable) && $lazyCallable[0] instanceof Greeter && $lazyCallable[1] === 'buildGreeting');
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));

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

echo "\n";
Expand Down
13 changes: 13 additions & 0 deletions examples/drupal/web/modules/custom/acme/acme.module
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
declare(strict_types=1);

use Drupal\acme\Greeter;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;

/**
Expand Down Expand Up @@ -80,3 +81,15 @@ function acme_request_age(): int

return $clock->secondsSinceRequest();
}

/**
* Submit handler of GreetingForm, which names it in its `#submit` list.
*
* @param array<string, mixed> $form
*/
function acme_greeting_form_submit(array &$form, FormStateInterface $form_state): void
{
// Try: find the references of acme_greeting_form_submit(), which list
// the string in GreetingForm::buildForm().
\Drupal::logger('acme')->info('Greeted @name.', ['@name' => $form_state->getValue('name')]);
}
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,15 @@ public function card(string $name): array
];
$build['more']['#type'] = 'details';
$build['more']['#title'] = $this->t('More');
// Try: go to the definition of buildGreeting, which lands on the
// method of Greeter, the class of the acme.greeter service, or of
// acme.greeter, which lands on its key in acme.services.yml. Find
// the references of Greeter::buildGreeting(), or rename it, and the
// string follows.
$build['later'] = [
'#lazy_builder' => ['acme.greeter:buildGreeting', [$name]],
'#create_placeholder' => true,
];

return $build;
}
Expand Down
Loading
Loading