mirror of
https://github.com/pterodactyl/panel.git
synced 2026-12-04 05:15:41 -05:00
scribe resource attribute
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pterodactyl\Extensions\Scribe\Attributes;
|
||||
|
||||
use Attribute;
|
||||
use Knuckles\Scribe\Attributes\ResponseFromApiResource;
|
||||
|
||||
/**
|
||||
* Documents a response rendered by one of our API resources, the way #[ResponseFromTransformer]
|
||||
* documents a Fractal one: the example is rendered from a factory model with the given
|
||||
* includes, object name and meta.
|
||||
*/
|
||||
#[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_FUNCTION | Attribute::TARGET_METHOD | Attribute::TARGET_CLASS)]
|
||||
class ResponseFromResource extends ResponseFromApiResource
|
||||
{
|
||||
/**
|
||||
* @param list<string> $factoryStates Factory states applied to the example model.
|
||||
* @param list<string> $with Relationships eager loaded onto the example model.
|
||||
* @param string|null $resourceKey The `object` of the rendered items; null renders null.
|
||||
* @param int|null $paginate Renders a list paginated by this many per page.
|
||||
* @param ApiPayload $meta Example values merged into the response envelope's
|
||||
* top-level meta key, mirroring the controller's
|
||||
* withMeta() output that rendering the resource alone
|
||||
* cannot reproduce.
|
||||
* @param string[] $include Includes to render so the documented response carries
|
||||
* the relationships the endpoint can embed.
|
||||
* @param string[] $withCount Relationship counts to load on the example model,
|
||||
* mirroring the controller's withCount() query.
|
||||
*/
|
||||
public function __construct(
|
||||
string $name,
|
||||
?string $model = null,
|
||||
int $status = 200,
|
||||
?string $description = '',
|
||||
bool $collection = false,
|
||||
array $factoryStates = [],
|
||||
array $with = [],
|
||||
public ?string $resourceKey = null,
|
||||
?int $paginate = null,
|
||||
public array $meta = [],
|
||||
public array $include = [],
|
||||
array $withCount = [],
|
||||
) {
|
||||
parent::__construct($name, $model, $status, $description, $collection, $factoryStates, $with, $paginate, withCount: $withCount);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ use Knuckles\Camel\Output\OutputEndpointData;
|
||||
use Knuckles\Scribe\Attributes\ResponseFromTransformer;
|
||||
use Knuckles\Scribe\Writing\OpenApiSpecGenerators\OpenApiGenerator;
|
||||
use Pterodactyl\Extensions\Scribe\Attributes\ResponseField;
|
||||
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromResource;
|
||||
use Pterodactyl\Extensions\Scribe\Support\PterodactylDocumentation;
|
||||
use Pterodactyl\Http\Middleware\Api\Admin\RequireSessionAuthentication;
|
||||
use Pterodactyl\Models\Permission;
|
||||
@@ -268,7 +269,7 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
|
||||
|
||||
/**
|
||||
* Applies field metadata declared as ResponseField attributes - on the
|
||||
* endpoint's transformer class, or on the controller method itself - to a
|
||||
* endpoint's transformer or API resource class, or on the controller method itself - to a
|
||||
* fractal attributes schema. This is how nullability, enums, and map/union
|
||||
* shapes that cannot be inferred from a single example reach the spec.
|
||||
*
|
||||
@@ -509,8 +510,9 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, class-string> map of "METHOD uri" to the transformer class
|
||||
* declared by the route action's attribute
|
||||
* @return array<string, class-string> map of "METHOD uri" to the transformer or API
|
||||
* resource class declared by the route action's
|
||||
* attribute
|
||||
*/
|
||||
private function transformerClasses(): array
|
||||
{
|
||||
@@ -526,10 +528,11 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
|
||||
continue;
|
||||
}
|
||||
|
||||
$attributes = (new ReflectionMethod($class, $method))->getAttributes(
|
||||
ResponseFromTransformer::class,
|
||||
ReflectionAttribute::IS_INSTANCEOF,
|
||||
);
|
||||
$reflection = new ReflectionMethod($class, $method);
|
||||
$attributes = [
|
||||
...$reflection->getAttributes(ResponseFromTransformer::class, ReflectionAttribute::IS_INSTANCEOF),
|
||||
...$reflection->getAttributes(ResponseFromResource::class, ReflectionAttribute::IS_INSTANCEOF),
|
||||
];
|
||||
if ($attributes === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,9 @@ namespace Pterodactyl\Extensions\Scribe\Strategies;
|
||||
use Closure;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Facades\Request as RequestFacade;
|
||||
use InvalidArgumentException;
|
||||
use Knuckles\Scribe\Attributes\ResponseFromApiResource;
|
||||
use Knuckles\Scribe\Attributes\ResponseFromTransformer as BaseResponseFromTransformer;
|
||||
use Knuckles\Scribe\Extracting\DatabaseTransactionHelpers;
|
||||
use Knuckles\Scribe\Extracting\Strategies\Responses\UseResponseAttributes;
|
||||
@@ -17,7 +19,11 @@ use League\Fractal\Resource\Collection;
|
||||
use League\Fractal\Resource\Item;
|
||||
use League\Fractal\Serializer\Serializer;
|
||||
use League\Fractal\TransformerAbstract;
|
||||
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromResource;
|
||||
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer;
|
||||
use Pterodactyl\Http\Resources\Api\ApiResource;
|
||||
use Pterodactyl\Http\Resources\Api\ApiResourceCollection;
|
||||
use Pterodactyl\Http\Resources\Api\Includes\IncludeSet;
|
||||
use Pterodactyl\Models\User;
|
||||
use Pterodactyl\Support\JsonValueGuard;
|
||||
use Pterodactyl\Transformers\Api\Application\BaseTransformer;
|
||||
@@ -68,28 +74,62 @@ class UsePterodactylResponseAttributes extends UseResponseAttributes
|
||||
$this->endDbTransaction();
|
||||
}
|
||||
|
||||
if ($attributeInstance instanceof ResponseFromTransformer && $attributeInstance->meta !== []) {
|
||||
$decoded = json_decode($content, true);
|
||||
if (is_array($decoded)) {
|
||||
$existingMeta = $decoded['meta'] ?? null;
|
||||
if (! is_array($existingMeta)) {
|
||||
$existingMeta = [];
|
||||
}
|
||||
return [
|
||||
'status' => $attributeInstance->status,
|
||||
'description' => $attributeInstance->description,
|
||||
'content' => $attributeInstance instanceof ResponseFromTransformer ? $this->withExampleMeta($content, $attributeInstance->meta) : $content,
|
||||
];
|
||||
}
|
||||
|
||||
$decoded['meta'] = array_merge($existingMeta, $attributeInstance->meta);
|
||||
$content = json_encode($decoded);
|
||||
/**
|
||||
* Renders #[ResponseFromResource] examples as getTransformerResponse() renders the
|
||||
* transformer ones: inside a transaction, for a root administrator, from a factory model
|
||||
* whose counts are loaded afterwards, with the attribute's object name and meta.
|
||||
*
|
||||
* @return array{status: int, description: string|null, content: string|false}
|
||||
*/
|
||||
protected function getApiResourceResponse(ResponseFromApiResource $attributeInstance): array
|
||||
{
|
||||
throw_unless($attributeInstance instanceof ResponseFromResource, InvalidArgumentException::class, 'Document API resource responses with #['.ResponseFromResource::class.'].');
|
||||
|
||||
$resourceClass = $this->resourceClass($attributeInstance);
|
||||
$modelInstantiator = function () use ($attributeInstance): Model {
|
||||
$factoryStates = $attributeInstance->factoryStates;
|
||||
$relations = $attributeInstance->with;
|
||||
$withCount = $attributeInstance->withCount;
|
||||
JsonValueGuard::assertValue($factoryStates);
|
||||
JsonValueGuard::assertValue($relations);
|
||||
JsonValueGuard::assertValue($withCount);
|
||||
|
||||
// withCount is applied after instantiation, as for transformers.
|
||||
$model = $this->instantiateExampleModel($attributeInstance->model, $this->stringList($factoryStates), $this->stringList($relations));
|
||||
throw_unless($model instanceof Model, InvalidArgumentException::class, 'The model referenced by #[ResponseFromResource] must be an Eloquent model.');
|
||||
|
||||
$counts = $this->stringList($withCount);
|
||||
if ($counts !== [] && $model->exists) {
|
||||
$model->loadCount($counts);
|
||||
}
|
||||
|
||||
return $model;
|
||||
};
|
||||
|
||||
$this->startDbTransaction();
|
||||
try {
|
||||
$this->authenticateGenerationRequest();
|
||||
$content = $this->fetchResourceContent($attributeInstance, $resourceClass, $modelInstantiator);
|
||||
} finally {
|
||||
$this->endDbTransaction();
|
||||
}
|
||||
|
||||
return [
|
||||
'status' => $attributeInstance->status,
|
||||
'description' => $attributeInstance->description,
|
||||
'content' => $content,
|
||||
'content' => $this->withExampleMeta($content, $attributeInstance->meta),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Transformers render user-dependent fields (ownership flags, permission-gated
|
||||
* Transformers and resources render user-dependent fields (ownership flags, permission-gated
|
||||
* includes), so give the console request a root administrator for the duration
|
||||
* of the fetch. The user row lives inside the surrounding transaction.
|
||||
*/
|
||||
@@ -155,6 +195,82 @@ class UsePterodactylResponseAttributes extends UseResponseAttributes
|
||||
return $fractal->createData($resource)->toJson();
|
||||
}
|
||||
|
||||
/**
|
||||
* Rendered like the transformer examples: only the attribute's includes, as deep as
|
||||
* Fractal's default of ten levels, and none of the eager loading a controller's response
|
||||
* batches first.
|
||||
*
|
||||
* @param class-string<ApiResource<*>> $resourceClass
|
||||
* @param Closure(): Model $modelInstantiator
|
||||
*/
|
||||
private function fetchResourceContent(ResponseFromResource $attribute, string $resourceClass, Closure $modelInstantiator): string
|
||||
{
|
||||
$includes = IncludeSet::parse($this->stringList($attribute->include));
|
||||
$request = RequestFacade::instance();
|
||||
|
||||
if (! $attribute->collection) {
|
||||
// Controllers add extension field values to responses about one resource. The
|
||||
// example shows the attribute without running installed extensions' code.
|
||||
$resource = (new $resourceClass($modelInstantiator()))
|
||||
->withExtensionFields(read: false)
|
||||
->withResourceKey($attribute->resourceKey);
|
||||
|
||||
return json_encode($resource->resolveFor($includes, $request), JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
$models = [$modelInstantiator()];
|
||||
$data = $attribute->paginate === null ? $models : new LengthAwarePaginator($models, count($models), $attribute->paginate);
|
||||
|
||||
$collection = (new ApiResourceCollection($data, $resourceClass))->withResourceKey($attribute->resourceKey);
|
||||
|
||||
return json_encode($collection->resolveFor($includes, $request), JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges an attribute's example meta into the rendered envelope's top-level meta, after
|
||||
* any pagination, mirroring what the controller adds and rendering alone cannot.
|
||||
*
|
||||
* @param ApiPayload $meta
|
||||
*/
|
||||
private function withExampleMeta(string $content, array $meta): string|false
|
||||
{
|
||||
if ($meta === []) {
|
||||
return $content;
|
||||
}
|
||||
|
||||
$decoded = json_decode($content, true);
|
||||
if (is_array($decoded)) {
|
||||
$existingMeta = $decoded['meta'] ?? null;
|
||||
if (! is_array($existingMeta)) {
|
||||
$existingMeta = [];
|
||||
}
|
||||
|
||||
$decoded['meta'] = array_merge($existingMeta, $meta);
|
||||
$content = json_encode($decoded);
|
||||
}
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves and validates the API resource class referenced by a #[ResponseFromResource]
|
||||
* attribute.
|
||||
*
|
||||
* @return class-string<ApiResource<*>>
|
||||
*/
|
||||
private function resourceClass(ResponseFromResource $attribute): string
|
||||
{
|
||||
if (! is_a($attribute->name, ApiResource::class, true)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'The class [%s] referenced by #[ResponseFromResource] must extend %s.',
|
||||
$attribute->name,
|
||||
ApiResource::class,
|
||||
));
|
||||
}
|
||||
|
||||
return $attribute->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves and validates the Fractal transformer class referenced by a
|
||||
* #[ResponseFromTransformer] attribute.
|
||||
|
||||
@@ -19,6 +19,7 @@ use Pterodactyl\Data\ServerState;
|
||||
use Pterodactyl\Http\Resources\Api\Concerns\BuildsResponse;
|
||||
use Pterodactyl\Http\Resources\Api\Includes\IncludedResource;
|
||||
use Pterodactyl\Http\Resources\Api\Includes\IncludeScope;
|
||||
use Pterodactyl\Http\Resources\Api\Includes\IncludeSet;
|
||||
use Pterodactyl\Services\Extensions\ExtensionFields;
|
||||
use Pterodactyl\Support\JsonEmptyObject;
|
||||
use UnexpectedValueException;
|
||||
@@ -141,14 +142,26 @@ abstract class ApiResource extends JsonResource implements IncludedResource
|
||||
final public function resolve($request = null): array
|
||||
{
|
||||
$request ??= $this->resolveRequestFromContainer();
|
||||
$scope = $this->rootScope($request);
|
||||
$includes = $this->includeSet($request);
|
||||
|
||||
$model = $this->model();
|
||||
if ($model instanceof Model) {
|
||||
$this->prepare(new ModelCollection([$model]), $scope, $request);
|
||||
$this->prepare(new ModelCollection([$model]), $includes->root(), $request);
|
||||
}
|
||||
|
||||
return $this->render($scope, $request, $this->hasResourceKey ? $this->resourceKey : $this->resourceName());
|
||||
return $this->resolveFor($includes, $request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the resource as the root of a response for $includes, without the eager
|
||||
* loading resolve() batches first. Documentation examples render this way, as they did
|
||||
* with Fractal.
|
||||
*
|
||||
* @return ApiResourceItem
|
||||
*/
|
||||
final public function resolveFor(IncludeSet $includes, Request $request): array
|
||||
{
|
||||
return $this->render($includes->root(), $request, $this->hasResourceKey ? $this->resourceKey : $this->resourceName());
|
||||
}
|
||||
|
||||
final public function resolveIncluded(IncludeScope $scope, Request $request): static
|
||||
|
||||
@@ -14,6 +14,7 @@ use Illuminate\Support\Collection;
|
||||
use Pterodactyl\Http\Resources\Api\Concerns\BuildsResponse;
|
||||
use Pterodactyl\Http\Resources\Api\Includes\IncludedResource;
|
||||
use Pterodactyl\Http\Resources\Api\Includes\IncludeScope;
|
||||
use Pterodactyl\Http\Resources\Api\Includes\IncludeSet;
|
||||
use Pterodactyl\Support\JsonEmptyObject;
|
||||
use Traversable;
|
||||
|
||||
@@ -68,11 +69,23 @@ class ApiResourceCollection extends AnonymousResourceCollection implements Inclu
|
||||
final public function resolve($request = null): array
|
||||
{
|
||||
$request ??= $this->resolveRequestFromContainer();
|
||||
$scope = $this->rootScope($request);
|
||||
$includes = $this->includeSet($request);
|
||||
|
||||
$this->prepare($scope, $request);
|
||||
$this->prepare($includes->root(), $request);
|
||||
|
||||
$list = $this->render($scope, $request);
|
||||
return $this->resolveFor($includes, $request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the list as the root of a response for $includes, without the eager loading
|
||||
* resolve() batches first. Documentation examples render this way, as they did with
|
||||
* Fractal.
|
||||
*
|
||||
* @return ApiResourceList
|
||||
*/
|
||||
final public function resolveFor(IncludeSet $includes, Request $request): array
|
||||
{
|
||||
$list = $this->render($includes->root(), $request);
|
||||
|
||||
$meta = $this->meta;
|
||||
if ($this->resource instanceof LengthAwarePaginator) {
|
||||
|
||||
@@ -6,7 +6,6 @@ namespace Pterodactyl\Http\Resources\Api\Concerns;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Pterodactyl\Http\Resources\Api\Includes\IncludeScope;
|
||||
use Pterodactyl\Http\Resources\Api\Includes\IncludeSet;
|
||||
|
||||
/**
|
||||
@@ -79,8 +78,11 @@ trait BuildsResponse
|
||||
return new JsonResponse($this->resolve($request));
|
||||
}
|
||||
|
||||
private function rootScope(Request $request): IncludeScope
|
||||
/**
|
||||
* The includes the request asked for, with the ones the controller always returns.
|
||||
*/
|
||||
private function includeSet(Request $request): IncludeSet
|
||||
{
|
||||
return IncludeSet::fromRequest($request, $this->forcedIncludes)->root();
|
||||
return IncludeSet::fromRequest($request, $this->forcedIncludes);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pterodactyl\Tests\Pest\Integration\Extensions\Scribe\ResponseFromResourceTest;
|
||||
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Knuckles\Scribe\Tools\DocumentationConfig;
|
||||
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
|
||||
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromResource;
|
||||
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer;
|
||||
use Pterodactyl\Extensions\Scribe\Strategies\UsePterodactylResponseAttributes;
|
||||
use Pterodactyl\Http\Resources\Api\Admin\ServerDatabaseResource;
|
||||
use Pterodactyl\Http\Resources\Api\Application\ServerVariableResource;
|
||||
use Pterodactyl\Http\Resources\Api\Client\DatabaseResource;
|
||||
use Pterodactyl\Models\Database;
|
||||
use Pterodactyl\Models\DatabaseHost;
|
||||
use Pterodactyl\Models\EggVariable;
|
||||
use Pterodactyl\Tests\Integration\IntegrationTestCase;
|
||||
use Pterodactyl\Transformers\Api\Admin\ServerDatabaseTransformer;
|
||||
use Pterodactyl\Transformers\Api\Application\ServerVariableTransformer;
|
||||
use Pterodactyl\Transformers\Api\Client\DatabaseTransformer;
|
||||
|
||||
/*
|
||||
* #[ResponseFromResource] must document a resource exactly as #[ResponseFromTransformer]
|
||||
* documented the transformer it replaces. Both render the first model in the database, so
|
||||
* the two examples are built from the same row.
|
||||
*/
|
||||
|
||||
uses(IntegrationTestCase::class, DatabaseTransactions::class);
|
||||
|
||||
beforeEach(function (): void {
|
||||
$server = $this->createServerModel();
|
||||
$host = DatabaseHost::factory()->create(['node_id' => $server->node_id]);
|
||||
Database::factory()->create(['server_id' => $server->id, 'database_host_id' => $host->id]);
|
||||
|
||||
$config = config('scribe');
|
||||
$config['examples']['models_source'] = ['databaseFirst'];
|
||||
|
||||
$this->strategy = new class(new DocumentationConfig($config)) extends UsePterodactylResponseAttributes
|
||||
{
|
||||
/** @return array{status: int, description: string|null, content: string|false} */
|
||||
public function render(ResponseFromTransformer|ResponseFromResource $attribute): array
|
||||
{
|
||||
return $attribute instanceof ResponseFromResource ? $this->getApiResourceResponse($attribute) : $this->getTransformerResponse($attribute);
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
test('resources are documented as their transformers were', function (ResponseFromTransformer $transformer, ResponseFromResource $resource, string $expected): void {
|
||||
$documented = $this->strategy->render($transformer);
|
||||
|
||||
expect($this->strategy->render($resource))->toBe($documented)
|
||||
->and($documented['content'])->toContain($expected);
|
||||
})->with([
|
||||
'an item with an include, a status and meta' => [
|
||||
new ResponseFromTransformer(ServerDatabaseTransformer::class, Database::class, status: 201, description: 'Database created.', resourceKey: 'database', meta: ['resource' => 'https://panel.example.test/api/admin/servers/1/databases/1'], include: ['password']),
|
||||
new ResponseFromResource(ServerDatabaseResource::class, Database::class, status: 201, description: 'Database created.', resourceKey: 'database', meta: ['resource' => 'https://panel.example.test/api/admin/servers/1/databases/1'], include: ['password']),
|
||||
'"relationships":{"password":{"object":"database_password"',
|
||||
],
|
||||
'a paginated list with meta after the pagination' => [
|
||||
new ResponseFromTransformer(ServerDatabaseTransformer::class, Database::class, collection: true, resourceKey: 'database', paginate: [IlluminatePaginatorAdapter::class, 50], meta: ['note' => 'example']),
|
||||
new ResponseFromResource(ServerDatabaseResource::class, Database::class, collection: true, resourceKey: 'database', paginate: 50, meta: ['note' => 'example']),
|
||||
'"meta":{"pagination":{"total":1,"count":1,"per_page":50,"current_page":1,"total_pages":1,"links":[]},"note":"example"}',
|
||||
],
|
||||
'an item without a resource key' => [
|
||||
new ResponseFromTransformer(DatabaseTransformer::class, Database::class, include: ['password']),
|
||||
new ResponseFromResource(DatabaseResource::class, Database::class, include: ['password']),
|
||||
'{"object":null,"attributes":',
|
||||
],
|
||||
'a list with counts loaded after the model and a gated include' => [
|
||||
new ResponseFromTransformer(ServerVariableTransformer::class, EggVariable::class, collection: true, resourceKey: 'server_variable', include: ['parent'], withCount: ['serverVariable']),
|
||||
new ResponseFromResource(ServerVariableResource::class, EggVariable::class, collection: true, resourceKey: 'server_variable', include: ['parent'], withCount: ['serverVariable']),
|
||||
'"server_variable_count":0,"relationships":{"parent":{"object":"null_resource","attributes":null}}',
|
||||
],
|
||||
]);
|
||||
Reference in New Issue
Block a user