Files
pterodactyl-panel/app/Services/Extensions/ExtensionFieldRegistry.php
Sky Mulleyandrobert dennis 71dd1911a5 Implement native support for hooking into forms with extensions (#7256)
## Problem

Extensions can render content before and after most admin pages, but not
inside the forms on them. The only exception was
`panel.users.detail.form`, and it could only re-render or validate the
user's existing fields. An extension had no way to add a field of its
own, because the Panel's save requests had nowhere to carry the value
and nothing loaded it back.

## Changes

### Slots inside every admin form

The create and edit forms for users, nodes, servers, eggs, locations,
mounts and database hosts each render a slot inside the form, such as
`panel.servers.create.form` and `panel.servers.detail.details.form`. The
slot receives the native `form`, the form's `kind` (`admin.server`), and
`mode` (`'create'` or `'edit'`). Edit slots also receive the saved
`resource`. Contributed `form.AppField` controls share the form's
validation, pending state and submit action.

### Extension-owned fields

An extension registers fields in its provider:

```php
$this->registerFormFields('admin.user', ['plan' => ['required', 'in:free,pro']]);

$this->registerFormFields(
    'admin.node',
    ['region' => ['required', 'string', 'max:32']],
    fn (Node $node): array => ['region' => NodeRegion::for($node)],
    fn (Node $node, array $values) => NodeRegion::store($node, $values['region']),
);
```

The 14 create and update endpoints accept an optional `extensions: {
[extensionId]: { [field]: value } }` body field. Each extension's rules
are applied as `extensions.{id}.{field}`, and only when the request
includes that extension's values. The extension's `save` callback runs
in the same database transaction as the core change, so a failure rolls
both back.

Server creation is the exception. Wings reads the new server while
provisioning it, so extension values are saved after provisioning
succeeds, outside the transaction.

For Node updates when Wings is unreachable. `UpdateNode` saves the node
and then throws `ConfigurationNotPersistedException` as a warning. The
node controller defers that exception until the extension values are
saved, so the node update is no longer rolled back.

`GET /api/admin/extensions/forms/{form}/{id}` returns every extension's
current values. It requires the resource's read permission. Edit pages
fetch it before rendering the form, but only when an extension has
registered fields for that form; the bootstrap payload now lists them
per extension in `forms`.

For users and servers the callbacks are optional, and values are stored
in the extension's scoped settings (`settings()->forUser($user)`,
`forServer($server)`). Values are limited to strings, numbers, booleans,
`null`, or lists of strings and numbers, which keeps the OpenAPI schema
and generated types concrete.

A `load` callback that throws, or returns an invalid value, is recorded
against the extension in the `form` phase. The frontend then hides that
extension's slot contributions on the edit page, so a save cannot
overwrite its stored values with defaults. Fields of a disabled or
failed extension are neither validated, saved nor loaded.

---------

Co-authored-by: robert dennis <31261583+robertdrakedennis@users.noreply.github.com>
2026-10-09 01:26:45 -04:00

103 lines
4.9 KiB
PHP

<?php
declare(strict_types=1);
namespace Pterodactyl\Services\Extensions;
use Illuminate\Contracts\Container\ContextualAttribute;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
use Pterodactyl\Extensions\Attributes\ApplicationApi;
use Pterodactyl\Extensions\Fields;
use ReflectionAttribute;
use ReflectionClass;
use ReflectionMethod;
use ReflectionNamedType;
/** The Fields classes extensions registered, keyed by model class and extension id. */
final class ExtensionFieldRegistry
{
/** @var array<class-string<Model>, array<string, ExtensionFieldEntry>> */
private array $fields = [];
/**
* @param class-string<Model> $model
* @param class-string $fields
*/
public function register(string $extension, string $model, string $fields, ExtensionRegistration $registration): void
{
throw_unless(in_array($model, ExtensionSettings::SCOPES, true), InvalidArgumentException::class, sprintf('Extension "%s" cannot add fields to %s: only users, servers, nodes, eggs, locations, mounts and database hosts accept them.', $extension, $model));
throw_unless(is_subclass_of($fields, Fields::class), InvalidArgumentException::class, sprintf('Extension "%s" registered %s for %s, which does not extend %s.', $extension, $fields, class_basename($model), Fields::class));
throw_if(method_exists($fields, 'values') !== method_exists($fields, 'save'), InvalidArgumentException::class, sprintf('%s must implement both values() and save(), or neither to let the panel store its values.', $fields));
throw_if(isset($this->fields[$model][$extension]), InvalidArgumentException::class, sprintf('Extension "%s" registered fields for %s more than once.', $extension, class_basename($model)));
$this->assertModelParameters($model, $fields);
$this->fields[$model][$extension] = [
'fields' => $fields,
'registration' => $registration,
'applicationApi' => (new ReflectionClass($fields))->getAttributes(ApplicationApi::class) !== [],
];
}
/**
* The Fields classes of extensions whose provider booted, keyed by extension id. The
* Application API only sees those marked #[ApplicationApi].
*
* @param class-string<Model> $model
* @return array<string, class-string<Fields>>
*/
public function for(string $model, bool $applicationApi = false): array
{
$fields = [];
foreach ($this->fields[$model] ?? [] as $extension => $entry) {
if ($entry['registration']->isActive() && (! $applicationApi || $entry['applicationApi'])) {
$fields[$extension] = $entry['fields'];
}
}
return $fields;
}
/** @return array<class-string<Model>, array<string, ExtensionFieldEntry>> */
public function snapshot(): array
{
return $this->fields;
}
/** @param array<class-string<Model>, array<string, ExtensionFieldEntry>> $fields */
public function restore(array $fields): void
{
$this->fields = $fields;
}
/**
* A parameter typed with a model receives the model the fields belong to, and every
* method but values() and save() also runs while that model is created, before it
* exists. A parameter of another model class, or one that does not accept null in those
* methods, would therefore get an empty model or fail: the author almost always wanted
* the signed-in user, which `#[CurrentUser] User $admin` provides.
*
* @param class-string<Model> $model
* @param class-string $fields
*/
private function assertModelParameters(string $model, string $fields): void
{
foreach (['authorize', 'rules', 'attributes', 'messages', 'secrets', 'values', 'save'] as $method) {
if (! method_exists($fields, $method)) {
continue;
}
foreach ((new ReflectionMethod($fields, $method))->getParameters() as $parameter) {
$type = $parameter->getType();
if (! $type instanceof ReflectionNamedType || ! is_a($type->getName(), Model::class, true) || $parameter->getAttributes(ContextualAttribute::class, ReflectionAttribute::IS_INSTANCEOF) !== []) {
continue;
}
$name = sprintf('%s::%s() parameter $%s', class_basename($fields), $method, $parameter->getName());
throw_unless(in_array($type->getName(), [$model, Model::class], true), InvalidArgumentException::class, sprintf('%s would receive an empty %s: only the %s the fields belong to is passed. Use #[CurrentUser] User for the signed-in user.', $name, class_basename($type->getName()), class_basename($model)));
throw_if(! in_array($method, ['values', 'save'], true) && ! $type->allowsNull(), InvalidArgumentException::class, sprintf('%s is null while the %s is created: make it nullable, or use #[CurrentUser] User for the signed-in user.', $name, class_basename($model)));
}
}
}
}