drop fractal

This commit is contained in:
robert dennis
2026-10-12 05:18:58 -04:00
parent e6bf9b7914
commit 4a74b49db0
46 changed files with 231 additions and 878 deletions
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Exceptions\Resource;
use Pterodactyl\Exceptions\PterodactylException;
class InvalidResourceLevelException extends PterodactylException {}
@@ -1,9 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Exceptions\Transformer;
use Pterodactyl\Exceptions\PterodactylException;
class InvalidTransformerLevelException extends PterodactylException {}
@@ -1,80 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Extensions\League\Fractal\Serializers;
use Illuminate\Support\Arr;
use League\Fractal\Serializer\ArraySerializer;
class PterodactylSerializer extends ArraySerializer
{
/**
* Serialize an item.
*
* @param array<string, mixed> $data
* @return array{object: string|null, attributes: array<string, mixed>}
*/
public function item(?string $resourceKey, array $data): array
{
return [
'object' => $resourceKey,
'attributes' => $data,
];
}
/**
* Serialize a collection.
*
* @param list<array<string, mixed>> $data
* @return array{object: string, data: list<array{object: string|null, attributes: array<string, mixed>}>}
*/
public function collection(?string $resourceKey, array $data): array
{
$response = [];
foreach ($data as $datum) {
$response[] = $this->item($resourceKey, $datum);
}
return [
'object' => 'list',
'data' => $response,
];
}
/**
* Serialize a null resource.
*
* @return array{object: string, attributes: null}
*/
public function null(): ?array
{
return [
'object' => 'null_resource',
'attributes' => null,
];
}
/**
* Merge the included resources with the parent resource being serialized.
*
* @param array<string, mixed> $transformedData
* @param array<string, mixed> $includedData
* @return array<string, mixed>
*/
public function mergeIncludes(array $transformedData, array $includedData): array
{
if ($includedData === []) {
return $transformedData;
}
$relationships = Arr::array($transformedData, 'relationships', []);
foreach ($includedData as $key => $datum) {
$relationships[$key] = $datum;
}
$transformedData['relationships'] = $relationships;
return $transformedData;
}
}
@@ -8,8 +8,8 @@ use Attribute;
use Knuckles\Scribe\Attributes\ResponseField as BaseResponseField;
/**
* Declares schema metadata for one field of a transformer's output, placed on
* the transformer class itself so the OpenAPI schema stays next to the code
* Declares schema metadata for one field of an API resource's attributes, placed on
* the resource class itself so the OpenAPI schema stays next to the code
* that produces the field. Field names are relative to the attributes object
* and may use dot paths (e.g. "feature_limits.databases").
*/
@@ -8,9 +8,8 @@ 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.
* Documents a response rendered by one of our API resources: 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
@@ -1,42 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Extensions\Scribe\Attributes;
use Attribute;
use Knuckles\Scribe\Attributes\ResponseFromTransformer as BaseResponseFromTransformer;
#[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_FUNCTION | Attribute::TARGET_METHOD | Attribute::TARGET_CLASS)]
class ResponseFromTransformer extends BaseResponseFromTransformer
{
/**
* @param list<string> $factoryStates Factory states applied to the example model.
* @param list<string> $with Relationships eager loaded onto the example model.
* @param array{}|array{class-string, int} $paginate Format: [adapter, numberPerPage].
* @param array<string, mixed> $meta Example values merged into the response envelope's
* top-level meta key, mirroring the controller's
* Fractal ->addMeta() output that transformer
* execution alone cannot reproduce.
* @param string[] $include Fractal includes to execute 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 = [],
?string $resourceKey = null,
array $paginate = [],
public array $meta = [],
public array $include = [],
public array $withCount = [],
) {
parent::__construct($name, $model, $status, $description, $collection, $factoryStates, $with, $resourceKey, $paginate);
}
}
@@ -11,7 +11,6 @@ use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Knuckles\Camel\Extraction\Response as ExtractedResponse;
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;
@@ -38,7 +37,7 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
private ?array $operationIds = null;
/** @var array<string, class-string>|null */
private ?array $transformerClasses = null;
private ?array $resourceClasses = null;
/** @var array<string, true>|null */
private ?array $sessionOnlyEndpoints = null;
@@ -159,9 +158,9 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
'AdminNodeSystemInformationResponse' => $this->adminNodeSystemInformationSchema(),
'AdminNodeUtilizationResponse' => $this->adminNodeUtilizationSchema(),
'AdminServerVariableAttributes' => $this->adminServerVariableAttributesSchema(),
'AdminServerVariableListResponse' => $this->fractalListSchema('AdminServerVariableResource'),
'AdminServerVariablePaginatedResponse' => $this->fractalPaginatedSchema('AdminServerVariableResource'),
'AdminServerVariableResource' => $this->fractalItemSchema('server_variable', 'AdminServerVariableAttributes'),
'AdminServerVariableListResponse' => $this->resourceListSchema('AdminServerVariableResource'),
'AdminServerVariablePaginatedResponse' => $this->resourcePaginatedSchema('AdminServerVariableResource'),
'AdminServerVariableResource' => $this->resourceItemSchema('server_variable', 'AdminServerVariableAttributes'),
'AdminSettingsResponse' => $this->adminSettingsSchema(),
'AdminVersionInformationResponse' => $this->adminVersionInformationSchema(),
'AuthLoginCheckpointResponse' => $this->authLoginCheckpointResponseSchema(),
@@ -184,12 +183,12 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
];
foreach ($groupedEndpoints as $group) {
foreach ($group['endpoints'] as $endpoint) {
$fractal = $this->fractalResponse($endpoint);
if ($fractal === null) {
$envelope = $this->exampleEnvelope($endpoint);
if ($envelope === null) {
continue;
}
foreach ($this->fractalComponents($endpoint, $fractal['resource']) as $component) {
foreach ($this->resourceComponents($endpoint, $envelope['resource']) as $component) {
$knownComponents[$component] = true;
}
}
@@ -197,15 +196,15 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
foreach ($groupedEndpoints as $group) {
foreach ($group['endpoints'] as $endpoint) {
$fractal = $this->fractalResponse($endpoint);
if ($fractal === null) {
$envelope = $this->exampleEnvelope($endpoint);
if ($envelope === null) {
continue;
}
$components = $this->fractalComponents($endpoint, $fractal['resource']);
$components = $this->resourceComponents($endpoint, $envelope['resource']);
$attributes = $components['attributes'];
if (! isset($schemas[$attributes])) {
$attributeValues = $fractal['attributes'];
$attributeValues = $envelope['attributes'];
if (str_ends_with($attributes, 'EggAttributes') && is_array($attributeValues['config'] ?? null)) {
foreach (['files', 'startup', 'logs', 'file_denylist'] as $declaredField) {
$attributeValues['config'][$declaredField] = [];
@@ -220,7 +219,7 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
}
$this->applyDeclaredFieldMetadata($schemas[$attributes], $endpoint);
if (isset($fractal['attributes']['extensions'])) {
if (isset($envelope['attributes']['extensions'])) {
$this->addExtensionFieldsToAttributesSchema($schemas[$attributes]);
}
@@ -234,20 +233,20 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
}
}
if (isset($fractal['relationships'])) {
$this->addRelationshipsToAttributesSchema($schemas[$attributes], $endpoint, $fractal['relationships'], $knownComponents);
if (isset($envelope['relationships'])) {
$this->addRelationshipsToAttributesSchema($schemas[$attributes], $endpoint, $envelope['relationships'], $knownComponents);
}
$schemas[$components['item']] ??= $this->fractalItemSchema($fractal['resource'], $attributes);
if (isset($fractal['meta'])) {
$this->addMetaToItemSchema($schemas[$components['item']], $fractal['meta']);
$schemas[$components['item']] ??= $this->resourceItemSchema($envelope['resource'], $attributes);
if (isset($envelope['meta'])) {
$this->addMetaToItemSchema($schemas[$components['item']], $envelope['meta']);
}
$schemas[$components['list']] ??= $this->fractalListSchema($components['item']);
$schemas[$components['page']] ??= $this->fractalPaginatedSchema($components['item']);
if (isset($fractal['top_meta'])) {
$this->addMetaToListSchema($schemas[$components['list']], $fractal['top_meta']);
$this->addMetaToPaginatedSchema($schemas[$components['page']], $fractal['top_meta']);
$schemas[$components['list']] ??= $this->resourceListSchema($components['item']);
$schemas[$components['page']] ??= $this->resourcePaginatedSchema($components['item']);
if (isset($envelope['top_meta'])) {
$this->addMetaToListSchema($schemas[$components['list']], $envelope['top_meta']);
$this->addMetaToPaginatedSchema($schemas[$components['page']], $envelope['top_meta']);
}
}
}
@@ -259,17 +258,17 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
/**
* Applies field metadata declared as ResponseField attributes - on the
* 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
* endpoint's API resource class, or on the controller method itself - to an
* attributes schema. This is how nullability, enums, and map/union
* shapes that cannot be inferred from a single example reach the spec.
*
* @param array<mixed> $schema
*/
private function applyDeclaredFieldMetadata(array &$schema, OutputEndpointData $endpoint): void
{
$transformer = $this->transformerClasses()[$this->anonymousEndpointKey(mb_strtoupper($endpoint->httpMethods[0]), $endpoint->uri)] ?? null;
if ($transformer !== null) {
foreach ((new ReflectionClass($transformer))->getAttributes(ResponseField::class) as $attribute) {
$resourceClass = $this->resourceClasses()[$this->anonymousEndpointKey(mb_strtoupper($endpoint->httpMethods[0]), $endpoint->uri)] ?? null;
if ($resourceClass !== null) {
foreach ((new ReflectionClass($resourceClass))->getAttributes(ResponseField::class) as $attribute) {
$field = $attribute->newInstance();
$schema = $this->applyFieldMetadata($schema, $field->name, [
'description' => $field->description,
@@ -522,14 +521,13 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
}
/**
* @return array<string, class-string> map of "METHOD uri" to the transformer or API
* resource class declared by the route action's
* attribute
* @return array<string, class-string> map of "METHOD uri" to the API resource class
* declared by the route action's attribute
*/
private function transformerClasses(): array
private function resourceClasses(): array
{
if ($this->transformerClasses !== null) {
return $this->transformerClasses;
if ($this->resourceClasses !== null) {
return $this->resourceClasses;
}
$map = [];
@@ -540,17 +538,13 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
continue;
}
$reflection = new ReflectionMethod($class, $method);
$attributes = [
...$reflection->getAttributes(ResponseFromTransformer::class, ReflectionAttribute::IS_INSTANCEOF),
...$reflection->getAttributes(ResponseFromResource::class, ReflectionAttribute::IS_INSTANCEOF),
];
$attributes = (new ReflectionMethod($class, $method))->getAttributes(ResponseFromResource::class, ReflectionAttribute::IS_INSTANCEOF);
if ($attributes === []) {
continue;
}
$transformer = $attributes[0]->newInstance()->name;
if (! class_exists($transformer)) {
$resourceClass = $attributes[0]->newInstance()->name;
if (! class_exists($resourceClass)) {
continue;
}
@@ -560,12 +554,12 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
}
if ($httpMethod !== 'HEAD' && $httpMethod !== 'OPTIONS') {
$map[$this->anonymousEndpointKey($httpMethod, $route->uri())] = $transformer;
$map[$this->anonymousEndpointKey($httpMethod, $route->uri())] = $resourceClass;
}
}
}
return $this->transformerClasses = $map;
return $this->resourceClasses = $map;
}
/** @return array<mixed> */
@@ -843,15 +837,15 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
*/
private function replaceSuccessResponseSchema(array &$pathItem, OutputEndpointData $endpoint): void
{
$fractal = $this->fractalResponse($endpoint);
if ($fractal === null) {
$envelope = $this->exampleEnvelope($endpoint);
if ($envelope === null) {
return;
}
$components = $this->fractalComponents($endpoint, $fractal['resource']);
$components = $this->resourceComponents($endpoint, $envelope['resource']);
$schema = match (true) {
$fractal['paginated'] => $components['page'],
$fractal['collection'] => $components['list'],
$envelope['paginated'] => $components['page'],
$envelope['collection'] => $components['list'],
default => $components['item'],
};
@@ -1710,15 +1704,15 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
/**
* @return array{attributes: string, item: string, list: string, page: string}
*/
private function fractalComponents(OutputEndpointData $endpoint, string $resource): array
private function resourceComponents(OutputEndpointData $endpoint, string $resource): array
{
return $this->fractalComponentNames($this->surface($endpoint), $resource);
return $this->resourceComponentNames($this->surface($endpoint), $resource);
}
/**
* @return array{attributes: string, item: string, list: string, page: string}
*/
private function fractalComponentNames(string $surface, string $resource): array
private function resourceComponentNames(string $surface, string $resource): array
{
$name = Str::of(ucfirst($surface).' '.$resource)
->studly()
@@ -1816,7 +1810,7 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
$componentKey = $kind === 'list' ? 'list' : 'item';
foreach ($this->relationshipResourceCandidates($relationship, $resource) as $candidate) {
$components = $this->fractalComponentNames($this->surface($endpoint), $candidate);
$components = $this->resourceComponentNames($this->surface($endpoint), $candidate);
if (isset($knownComponents[$components[$componentKey]])) {
// Any include resolves to a null resource when the viewer lacks
// permission for it, so relationships are documented as a union.
@@ -1873,7 +1867,7 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
}
/** @return array<mixed> */
private function fractalItemSchema(string $resource, string $attributesSchema): array
private function resourceItemSchema(string $resource, string $attributesSchema): array
{
return [
'type' => 'object',
@@ -1962,7 +1956,7 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
}
/** @return array{type: string, required: list<string>, properties: array<string, array<string, mixed>>} */
private function fractalListSchema(string $itemSchema): array
private function resourceListSchema(string $itemSchema): array
{
return [
'type' => 'object',
@@ -1981,9 +1975,9 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
}
/** @return array<mixed> */
private function fractalPaginatedSchema(string $itemSchema): array
private function resourcePaginatedSchema(string $itemSchema): array
{
$schema = $this->fractalListSchema($itemSchema);
$schema = $this->resourceListSchema($itemSchema);
$schema['required'][] = 'meta';
$schema['properties']['meta'] = [
'type' => 'object',
@@ -2576,7 +2570,7 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
/**
* @return array{resource: string, attributes: array<mixed>, relationships?: array<mixed>, collection: bool, paginated: bool, meta?: array<mixed>, top_meta?: array<mixed>}|null
*/
private function fractalResponse(OutputEndpointData $endpoint): ?array
private function exampleEnvelope(OutputEndpointData $endpoint): ?array
{
foreach ($endpoint->responses as $response) {
if (! $response instanceof ExtractedResponse) {
@@ -2608,7 +2602,7 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
$attributes = $item['attributes'];
$relationships = $this->extractRelationships($attributes);
$pagination = $decoded['meta'] ?? null;
$fractal = [
$envelope = [
'resource' => is_string($item['object'] ?? null) ? $item['object'] : 'resource',
'attributes' => $attributes,
'collection' => true,
@@ -2616,28 +2610,28 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
];
if (isset($item['meta']) && is_array($item['meta'])) {
$fractal['meta'] = $item['meta'];
$envelope['meta'] = $item['meta'];
}
if (isset($decoded['meta']) && is_array($decoded['meta'])) {
$topMeta = $decoded['meta'];
unset($topMeta['pagination']);
if ($topMeta !== []) {
$fractal['top_meta'] = $topMeta;
$envelope['top_meta'] = $topMeta;
}
}
if ($relationships !== null) {
$fractal['relationships'] = $relationships;
$envelope['relationships'] = $relationships;
}
return $fractal;
return $envelope;
}
if (is_string($decoded['object'] ?? null) && is_array($decoded['attributes'] ?? null)) {
$attributes = $decoded['attributes'];
$relationships = $this->extractRelationships($attributes);
$fractal = [
$envelope = [
'resource' => $decoded['object'],
'attributes' => $attributes,
'collection' => false,
@@ -2645,14 +2639,14 @@ class PterodactylOpenApiGenerator extends OpenApiGenerator
];
if (isset($decoded['meta']) && is_array($decoded['meta'])) {
$fractal['meta'] = $decoded['meta'];
$envelope['meta'] = $decoded['meta'];
}
if ($relationships !== null) {
$fractal['relationships'] = $relationships;
$envelope['relationships'] = $relationships;
}
return $fractal;
return $envelope;
}
}
@@ -10,75 +10,22 @@ 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;
use League\Fractal\Manager;
use League\Fractal\Pagination\PaginatorInterface;
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 ReflectionClass;
class UsePterodactylResponseAttributes extends UseResponseAttributes
{
use DatabaseTransactionHelpers;
/**
* Replaces the vendor TransformerResponseTools path, which crashes on
* unpaginated collections and drops the resource key for them, so the
* serialized "object" name would fall back to "resource".
*
* @return array{status: int, description: string|null, content: string|false}
*/
protected function getTransformerResponse(BaseResponseFromTransformer $attributeInstance): array
{
// withCount is applied after instantiation: passing it through to Scribe
// makes the factory helper spawn bare related factories, which fail on
// models whose factories require sibling attributes.
$withCount = $attributeInstance instanceof ResponseFromTransformer ? $attributeInstance->withCount : [];
$transformerClass = $this->transformerClass($attributeInstance);
$modelInstantiator = function () use ($attributeInstance, $withCount, $transformerClass) {
$model = $this->instantiateExampleModel(
$attributeInstance->model,
$this->stringList($attributeInstance->factoryStates),
$this->stringList($attributeInstance->with),
(new ReflectionClass($transformerClass))->getMethod('transform'),
);
if ($withCount !== [] && $model instanceof Model && $model->exists) {
$model->loadCount($withCount);
}
return $model;
};
$this->startDbTransaction();
try {
$this->authenticateGenerationRequest();
$content = $this->fetchTransformerContent($attributeInstance, $modelInstantiator);
} finally {
$this->endDbTransaction();
}
return [
'status' => $attributeInstance->status,
'description' => $attributeInstance->description,
'content' => $attributeInstance instanceof ResponseFromTransformer ? $this->withExampleMeta($content, $attributeInstance->meta) : $content,
];
}
/**
* 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.
* Renders #[ResponseFromResource] examples 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}
*/
@@ -88,7 +35,9 @@ class UsePterodactylResponseAttributes extends UseResponseAttributes
$resourceClass = $this->resourceClass($attributeInstance);
$modelInstantiator = function () use ($attributeInstance): Model {
// withCount is applied after instantiation, as for transformers.
// Counts are loaded after instantiation: passing withCount through to Scribe
// makes the factory helper spawn bare related factories, which fail on models
// whose factories require sibling attributes.
$model = $this->instantiateExampleModel($attributeInstance->model, $this->stringList($attributeInstance->factoryStates), $this->stringList($attributeInstance->with));
throw_unless($model instanceof Model, InvalidArgumentException::class, 'The model referenced by #[ResponseFromResource] must be an Eloquent model.');
@@ -116,9 +65,9 @@ class UsePterodactylResponseAttributes extends UseResponseAttributes
}
/**
* 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.
* 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.
*/
private function authenticateGenerationRequest(): void
{
@@ -127,59 +76,9 @@ class UsePterodactylResponseAttributes extends UseResponseAttributes
resolve('request')->setUserResolver(fn () => $user);
}
private function fetchTransformerContent(BaseResponseFromTransformer $attribute, Closure $modelInstantiator): string
{
$fractal = new Manager;
if ($serializer = $this->config->get('fractal.serializer')) {
throw_unless(is_string($serializer), InvalidArgumentException::class, 'The configured Fractal serializer must be a class name.');
$resolvedSerializer = resolve($serializer);
throw_unless($resolvedSerializer instanceof Serializer, InvalidArgumentException::class, 'The configured Fractal serializer must implement the serializer contract.');
$fractal->setSerializer($resolvedSerializer);
}
if ($attribute instanceof ResponseFromTransformer && $attribute->include !== []) {
$fractal->parseIncludes($attribute->include);
}
$transformerClass = $this->transformerClass($attribute);
$transformer = resolve($transformerClass);
throw_unless($transformer instanceof TransformerAbstract, InvalidArgumentException::class, "Transformer [$transformerClass] must extend ".TransformerAbstract::class.'.');
if (! $attribute->collection) {
$resource = new Item($modelInstantiator(), $transformer, $attribute->resourceKey);
return $fractal->createData($resource)->toJson();
}
$models = [$modelInstantiator()];
$resource = new Collection($models, $transformer, $attribute->resourceKey);
if ($attribute->paginate !== []) {
$adapter = $attribute->paginate[0];
$perPage = $attribute->paginate[1] ?? count($models);
if (! is_string($adapter) || ! is_a($adapter, PaginatorInterface::class, true)) {
throw new InvalidArgumentException(sprintf(
'The paginator adapter referenced by #[ResponseFromTransformer] must be a class-string implementing %s.',
PaginatorInterface::class,
));
}
throw_unless(is_int($perPage), InvalidArgumentException::class, 'The paginator page size must be an integer.');
$paginator = new LengthAwarePaginator($models, count($models), $perPage);
$resource->setPaginator(new $adapter($paginator));
}
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.
* Only the attribute's includes, up to ten levels deep, and none of the eager loading a
* controller's response batches first.
*
* @param class-string<ApiResource<*>> $resourceClass
* @param Closure(): Model $modelInstantiator
@@ -252,25 +151,6 @@ class UsePterodactylResponseAttributes extends UseResponseAttributes
return $attribute->name;
}
/**
* Resolves and validates the Fractal transformer class referenced by a
* #[ResponseFromTransformer] attribute.
*
* @return class-string<TransformerAbstract>
*/
private function transformerClass(BaseResponseFromTransformer $attribute): string
{
if (! is_a($attribute->name, TransformerAbstract::class, true)) {
throw new InvalidArgumentException(sprintf(
'The class [%s] referenced by #[ResponseFromTransformer] must extend %s.',
$attribute->name,
TransformerAbstract::class,
));
}
return $attribute->name;
}
/**
* @param array<mixed> $values
* @return list<string>
@@ -1,64 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Extensions\Spatie\Fractalistic;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use League\Fractal\Scope;
use League\Fractal\TransformerAbstract;
use Pterodactyl\Extensions\League\Fractal\Serializers\PterodactylSerializer;
use Spatie\Fractal\Fractal as SpatieFractal;
use Spatie\Fractalistic\Exceptions\InvalidTransformation;
use Spatie\Fractalistic\Exceptions\NoTransformerSpecified;
use UnexpectedValueException;
class Fractal extends SpatieFractal
{
/**
* Serialize a non-null API resource.
*
* @return array<string, mixed>
*
* @throws InvalidTransformation
* @throws NoTransformerSpecified
*/
public function toResponseArray(): array
{
$payload = parent::toArray();
throw_if($payload === null, UnexpectedValueException::class, 'A Fractal API response cannot use a null resource.');
return $payload;
}
/**
* Create fractal data.
*
* @throws InvalidTransformation
* @throws NoTransformerSpecified
*/
public function createData(): Scope
{
$this->serializer ??= new PterodactylSerializer;
// Automatically set the paginator on the response object if the
// data being provided implements a paginator.
if (($this->paginator) === null && $this->data instanceof LengthAwarePaginator) {
$this->paginator = new IlluminatePaginatorAdapter($this->data);
}
// If the resource name is not set attempt to pull it off the transformer
// itself and set it automatically.
if (
($this->resourceName) === null
&& $this->transformer instanceof TransformerAbstract
&& method_exists($this->transformer, 'getResourceName')
) {
$this->resourceName = $this->transformer->getResourceName();
}
return parent::createData();
}
}
-28
View File
@@ -1,28 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Facades;
use Illuminate\Support\Facades\Facade;
use League\Fractal\TransformerAbstract;
use Pterodactyl\Extensions\Spatie\Fractalistic\Fractal as Fractalistic;
/**
* A fresh Fractal instance per call, with the request's includes already parsed.
*
* @method static Fractalistic item(mixed $data = null, TransformerAbstract|callable|null $transformer = null, string|null $resourceName = null)
* @method static Fractalistic collection(mixed $data = null, TransformerAbstract|callable|null $transformer = null, string|null $resourceName = null)
* @method static Fractalistic transformWith(TransformerAbstract|callable $transformer)
*
* @see Fractalistic
*/
class Fractal extends Facade
{
protected static $cached = false;
protected static function getFacadeAccessor(): string
{
return Fractalistic::class;
}
}
@@ -57,7 +57,7 @@ class AllocationController extends AdminApiController
#[ResponseFromResource(AllocationResource::class, Allocation::class, description: 'Allocations returned.', collection: true, resourceKey: 'allocation', paginate: 50)]
public function index(GetAllocationsRequest $request, Node $node): ApiResourceCollection
{
// Eager-load the owning server so the transformer avoids an N+1 on server name.
// Eager-load the owning server so the resource avoids an N+1 on server name.
$query = $node->allocations()->with('server');
// An empty filter[server_id] reaches us as null because of ConvertEmptyStringsToNull,
@@ -6,7 +6,7 @@ namespace Pterodactyl\Http\Resources\Api\Admin;
use Illuminate\Database\Eloquent\Model;
use Pterodactyl\Data\ServerState;
use Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException;
use Pterodactyl\Exceptions\Resource\InvalidResourceLevelException;
use Pterodactyl\Http\Resources\Api\ApiResource;
/**
@@ -39,11 +39,11 @@ abstract class AdminResource extends ApiResource
* @param Model|ServerState|array<mixed> $data
* @return TNested
*
* @throws InvalidTransformerLevelException
* @throws InvalidResourceLevelException
*/
protected function makeResource(string $resource, Model|ServerState|array $data): ApiResource
{
throw_unless(is_subclass_of($resource, self::class), InvalidTransformerLevelException::class, "Resource [$resource] must extend ".self::class.'.');
throw_unless(is_subclass_of($resource, self::class), InvalidResourceLevelException::class, "Resource [$resource] must extend ".self::class.'.');
return parent::makeResource($resource, $data);
}
@@ -6,7 +6,7 @@ namespace Pterodactyl\Http\Resources\Api\Application;
use Illuminate\Database\Eloquent\Model;
use Pterodactyl\Data\ServerState;
use Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException;
use Pterodactyl\Exceptions\Resource\InvalidResourceLevelException;
use Pterodactyl\Http\Resources\Api\ApiResource;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Services\Acl\Api\AdminAcl;
@@ -55,11 +55,11 @@ abstract class ApplicationResource extends ApiResource
* @param Model|ServerState|array<mixed> $data
* @return TNested
*
* @throws InvalidTransformerLevelException
* @throws InvalidResourceLevelException
*/
protected function makeResource(string $resource, Model|ServerState|array $data): ApiResource
{
throw_unless(is_subclass_of($resource, self::class), InvalidTransformerLevelException::class, "Resource [$resource] must extend ".self::class.'.');
throw_unless(is_subclass_of($resource, self::class), InvalidResourceLevelException::class, "Resource [$resource] must extend ".self::class.'.');
return parent::makeResource($resource, $data);
}
@@ -7,7 +7,7 @@ namespace Pterodactyl\Http\Resources\Api\Client;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
use Pterodactyl\Data\ServerState;
use Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException;
use Pterodactyl\Exceptions\Resource\InvalidResourceLevelException;
use Pterodactyl\Http\Resources\Api\ApiResource;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\User;
@@ -55,11 +55,11 @@ abstract class ClientResource extends ApiResource
* @param Model|ServerState|array<mixed> $data
* @return TNested
*
* @throws InvalidTransformerLevelException
* @throws InvalidResourceLevelException
*/
protected function makeResource(string $resource, Model|ServerState|array $data): ApiResource
{
throw_unless(is_subclass_of($resource, self::class), InvalidTransformerLevelException::class, "Resource [$resource] must extend ".self::class.'.');
throw_unless(is_subclass_of($resource, self::class), InvalidResourceLevelException::class, "Resource [$resource] must extend ".self::class.'.');
return parent::makeResource($resource, $data);
}
+1 -2
View File
@@ -56,8 +56,7 @@ class Allocation extends Model
use HasHashid;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'allocation';
+1 -2
View File
@@ -82,8 +82,7 @@ class ApiKey extends Model implements HasAbilities
use HasFactory;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'api_key';
+1 -2
View File
@@ -36,8 +36,7 @@ class Database extends Model
use HasFactory;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'server_database';
+1 -2
View File
@@ -34,8 +34,7 @@ class DatabaseHost extends Model
use HasFactory;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'database_host';
+1 -2
View File
@@ -89,8 +89,7 @@ class Egg extends Model implements Identifiable
use HasVersion4Uuids;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'egg';
+1 -2
View File
@@ -39,8 +39,7 @@ class EggVariable extends Model
use HasFactory;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'egg_variable';
+1 -2
View File
@@ -27,8 +27,7 @@ class Location extends Model
use HasFactory;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'location';
+1 -2
View File
@@ -40,8 +40,7 @@ class Mount extends Model implements Identifiable
use HasRealtimeIdentifier;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'mount';
+1 -2
View File
@@ -71,8 +71,7 @@ class Node extends Model implements Identifiable
use Notifiable;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'node';
+1 -2
View File
@@ -13,8 +13,7 @@ use Illuminate\Support\Collection;
class Permission extends Model
{
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'subuser_permission';
+1 -2
View File
@@ -57,8 +57,7 @@ class Schedule extends Model
use HasHashid;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'server_schedule';
+1 -2
View File
@@ -125,8 +125,7 @@ class Server extends Model implements Identifiable
use Notifiable;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'server';
+1 -2
View File
@@ -35,8 +35,7 @@ class ServerTransfer extends Model
use HasFactory;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'server_transfer';
+1 -2
View File
@@ -22,8 +22,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ServerVariable extends Model
{
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'server_variable';
+1 -2
View File
@@ -33,8 +33,7 @@ class Subuser extends Model
use Notifiable;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'server_subuser';
+1 -2
View File
@@ -42,8 +42,7 @@ class Tag extends Model
use HasFactory;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'tag';
+1 -2
View File
@@ -46,8 +46,7 @@ class Task extends Model
use HasHashid;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'schedule_task';
+1 -2
View File
@@ -124,8 +124,7 @@ class User extends Authenticatable implements Identifiable
public const int USER_LEVEL_ADMIN = 1;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
* The resource name for this model in API responses.
*/
public const string RESOURCE_NAME = 'user';
-7
View File
@@ -23,12 +23,9 @@ use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Password;
use Knuckles\Scribe\Scribe;
use League\Fractal\Manager;
use Pterodactyl\Enum\ResourceLimit;
use Pterodactyl\Extensions\Illuminate\Auth\Passwords\PasswordBrokerManager;
use Pterodactyl\Extensions\Scribe\Support\PathParameterNames;
use Pterodactyl\Extensions\Spatie\Fractalistic\Fractal;
use Pterodactyl\Http\Resources\Api\Includes\IncludeSet;
use Pterodactyl\Models\Allocation;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Models\Backup;
@@ -130,10 +127,6 @@ class AppServiceProvider extends ServiceProvider
$this->app->extend('auth.password', fn (): PasswordBrokerManager => new PasswordBrokerManager($this->app));
$this->app->bind(fn (): Fractal => (new Fractal(new Manager))
->parseIncludes(IncludeSet::fromRequest($this->app->make(Request::class))->requestedNames())
->limitRecursion(2));
// Only load the settings service provider if the environment
// is configured to allow it.
if (! config('pterodactyl.load_environment_only', false) && ! $this->app->environment('testing')) {
-1
View File
@@ -40,7 +40,6 @@
"pragmarx/google2fa": "~8.0.3",
"predis/predis": "^3.3.0",
"s1lentium/iptools": "~1.2.0",
"spatie/laravel-fractal": "^6.3.2",
"spatie/laravel-query-builder": "^6.3.6",
"symfony/http-client": "^7.4.0",
"symfony/mailgun-mailer": "^7.4.0",
Generated
+1 -214
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "fa93e3c21e1f9e994ca671da3a7c7ea8",
"content-hash": "78448ec80edd2977e198452c42c2cf8a",
"packages": [
{
"name": "aws/aws-crt-php",
@@ -2560,76 +2560,6 @@
},
"time": "2026-01-23T15:30:45+00:00"
},
{
"name": "league/fractal",
"version": "0.20.2",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/fractal.git",
"reference": "573ca2e0e348a7fe573a3e8fbc29a6588ece8c4e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/fractal/zipball/573ca2e0e348a7fe573a3e8fbc29a6588ece8c4e",
"reference": "573ca2e0e348a7fe573a3e8fbc29a6588ece8c4e",
"shasum": ""
},
"require": {
"php": ">=7.4"
},
"require-dev": {
"doctrine/orm": "^2.5",
"illuminate/contracts": "~5.0",
"laminas/laminas-paginator": "~2.12",
"mockery/mockery": "^1.3",
"pagerfanta/pagerfanta": "~1.0.0|~4.0.0",
"phpstan/phpstan": "^1.4",
"phpunit/phpunit": "^9.5",
"squizlabs/php_codesniffer": "~3.4",
"vimeo/psalm": "^4.30"
},
"suggest": {
"illuminate/pagination": "The Illuminate Pagination component.",
"laminas/laminas-paginator": "Laminas Framework Paginator",
"pagerfanta/pagerfanta": "Pagerfanta Paginator"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "0.20.x-dev"
}
},
"autoload": {
"psr-4": {
"League\\Fractal\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Phil Sturgeon",
"email": "me@philsturgeon.uk",
"homepage": "http://philsturgeon.uk/",
"role": "Developer"
}
],
"description": "Handle the output of complex data structures ready for API output.",
"homepage": "http://fractal.thephpleague.com/",
"keywords": [
"api",
"json",
"league",
"rest"
],
"support": {
"issues": "https://github.com/thephpleague/fractal/issues",
"source": "https://github.com/thephpleague/fractal/tree/0.20.2"
},
"time": "2025-02-14T21:33:14+00:00"
},
{
"name": "league/mime-type-detection",
"version": "1.17.0",
@@ -4864,149 +4794,6 @@
],
"time": "2024-02-20T11:51:46+00:00"
},
{
"name": "spatie/fractalistic",
"version": "2.11.1",
"source": {
"type": "git",
"url": "https://github.com/spatie/fractalistic.git",
"reference": "85d6ff9a93f00d902e17924bb1475163b373c890"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/spatie/fractalistic/zipball/85d6ff9a93f00d902e17924bb1475163b373c890",
"reference": "85d6ff9a93f00d902e17924bb1475163b373c890",
"shasum": ""
},
"require": {
"league/fractal": "^0.20.1",
"php": "^7.4|^8.0"
},
"require-dev": {
"illuminate/pagination": "~5.3.0|~5.4.0|^9.0|^13.0",
"pestphp/pest": "^1.22",
"phpunit/phpunit": "^9.0"
},
"type": "library",
"autoload": {
"psr-4": {
"Spatie\\Fractalistic\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Freek Van der Herten",
"email": "freek@spatie.be",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"description": "A developer friendly wrapper around Fractal",
"homepage": "https://github.com/spatie/fractalistic",
"keywords": [
"api",
"fractal",
"fractalistic",
"spatie",
"transform"
],
"support": {
"issues": "https://github.com/spatie/fractalistic/issues",
"source": "https://github.com/spatie/fractalistic/tree/2.11.1"
},
"funding": [
{
"url": "https://github.com/spatie",
"type": "github"
}
],
"time": "2026-02-21T21:10:25+00:00"
},
{
"name": "spatie/laravel-fractal",
"version": "6.4.0",
"source": {
"type": "git",
"url": "https://github.com/spatie/laravel-fractal.git",
"reference": "d34114259233540dcb405e45dff863164fb426c5"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/spatie/laravel-fractal/zipball/d34114259233540dcb405e45dff863164fb426c5",
"reference": "d34114259233540dcb405e45dff863164fb426c5",
"shasum": ""
},
"require": {
"illuminate/contracts": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
"illuminate/support": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
"league/fractal": "^0.20.1|^0.20",
"nesbot/carbon": "^2.63|^3.0",
"php": "^8.0",
"spatie/fractalistic": "^2.9.5|^2.9",
"spatie/laravel-package-tools": "^1.11"
},
"require-dev": {
"ext-json": "*",
"orchestra/testbench": "^7.0|^8.0|^9.2|^10.0|^11.0",
"pestphp/pest": "^1.22|^2.34|^3.0|^4.0"
},
"type": "library",
"extra": {
"laravel": {
"aliases": {
"Fractal": "Spatie\\Fractal\\Facades\\Fractal"
},
"providers": [
"Spatie\\Fractal\\FractalServiceProvider"
]
}
},
"autoload": {
"files": [
"src/helpers.php"
],
"psr-4": {
"Spatie\\Fractal\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Freek Van der Herten",
"email": "freek@spatie.be",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"description": "An easy to use Fractal integration for Laravel applications",
"homepage": "https://github.com/spatie/laravel-fractal",
"keywords": [
"api",
"fractal",
"laravel",
"laravel-fractal",
"lumen",
"spatie",
"transform"
],
"support": {
"source": "https://github.com/spatie/laravel-fractal/tree/6.4.0"
},
"funding": [
{
"url": "https://spatie.be/open-source/support-us",
"type": "custom"
}
],
"time": "2026-02-21T15:58:07+00:00"
},
{
"name": "spatie/laravel-package-tools",
"version": "1.93.2",
-35
View File
@@ -1,35 +0,0 @@
<?php
declare(strict_types=1);
use League\Fractal\Serializer\JsonApiSerializer;
return [
/*
|--------------------------------------------------------------------------
| Default Serializer
|--------------------------------------------------------------------------
|
| The default serializer to be used when performing a transformation. It
| may be left empty to use Fractal's default one. This can either be a
| string or a League\Fractal\Serializer\SerializerAbstract subclass.
|
*/
'default_serializer' => JsonApiSerializer::class,
/*
|--------------------------------------------------------------------------
| Auto Includes
|--------------------------------------------------------------------------
|
| If enabled Fractal will automatically add the includes who's
| names are present in the `include` request parameter.
|
*/
'auto_includes' => [
'enabled' => true,
'request_key' => 'include',
],
];
-6
View File
@@ -11,7 +11,6 @@ use Knuckles\Scribe\Extracting\Strategies\QueryParameters\GetFromFormRequest;
use Knuckles\Scribe\Extracting\Strategies\Responses\ResponseCalls;
use Knuckles\Scribe\Extracting\Strategies\Responses\UseResponseAttributes;
use Knuckles\Scribe\Extracting\Strategies\StaticData;
use Pterodactyl\Extensions\League\Fractal\Serializers\PterodactylSerializer;
use Pterodactyl\Extensions\Scribe\OpenApi\PterodactylOpenApiGenerator;
use Pterodactyl\Extensions\Scribe\Strategies\InferPterodactylBodyParameters;
use Pterodactyl\Extensions\Scribe\Strategies\InferPterodactylResponses;
@@ -283,9 +282,4 @@ return [
// Scribe will try to start database transactions, so no changes are persisted to your database.
// Tell Scribe which connections should be transacted here. If you only use one db connection, you can leave this as is.
'database_connections_to_transact' => [config('database.default')],
'fractal' => [
// If you are using a custom serializer with league/fractal, you can specify it here.
'serializer' => PterodactylSerializer::class,
],
];
-2
View File
@@ -60,5 +60,3 @@ parameters:
identifier: argument.type
message: '#usePersonalAccessTokenModel#'
path: app/Providers/AuthServiceProvider.php
excludePaths:
- app/Extensions/Spatie/Fractalistic/Fractal.php
+1 -1
View File
@@ -1,4 +1,4 @@
// Fractal returns a NullResource for any include the viewer lacks permission for.
// The API returns a NullResource for any include the viewer lacks permission for.
interface NullResourceLike {
object: 'null_resource';
+1 -2
View File
@@ -11,8 +11,7 @@ use Symfony\Component\Yaml\Yaml;
/*
* Pins the generated OpenAPI document to a committed baseline, so changing how responses are
* produced (the Fractal to API Resources port) cannot change the documented contract without
* a visible diff. Regenerate the specification and the clients first, then run this test:
* produced cannot change the documented contract without a visible diff. Regenerate the specification and the clients first, then run this test:
*
* npm run api:refresh && npm run sdk:generate
* composer docs:openapi:baseline
@@ -25,9 +25,8 @@ use Pterodactyl\Tests\Integration\Api\Admin\AdminApiIntegrationTestCase;
use Pterodactyl\Tests\Integration\Api\Snapshots\SnapshotWorld as World;
/*
* Golden snapshots of every Fractal-backed Admin API response, recorded before the Fractal
* to API Resources port so the port can prove it changed no byte. Each dataset entry is one
* scenario: a fresh deterministic world (see SnapshotWorld) acting as its root administrator,
* Golden snapshots of every Admin API response that renders a resource, so a change to how
* responses are built cannot change a byte unnoticed. Each dataset entry is one scenario: a fresh deterministic world (see SnapshotWorld) acting as its root administrator,
* and the list of requests whose raw responses make up its snapshot file.
*/
@@ -20,9 +20,8 @@ use Pterodactyl\Tests\Integration\Api\Application\ApplicationApiIntegrationTestC
use Pterodactyl\Tests\Integration\Api\Snapshots\SnapshotWorld as World;
/*
* Golden snapshots of every Fractal-backed Application API response, recorded before the
* Fractal to API Resources port so the port can prove it changed no byte. Each dataset entry
* is one scenario: a fresh deterministic world (see SnapshotWorld), one actor, and the list
* Golden snapshots of every Application API response that renders a resource, so a change to
* how responses are built cannot change a byte unnoticed. Each dataset entry is one scenario: a fresh deterministic world (see SnapshotWorld), one actor, and the list
* of requests whose raw responses make up its snapshot file.
*/
@@ -9,9 +9,8 @@ use Pterodactyl\Tests\Integration\Api\Client\ClientApiIntegrationTestCase;
use Pterodactyl\Tests\Integration\Api\Snapshots\SnapshotWorld as World;
/*
* Golden snapshots of every Fractal-backed Client API response, recorded before the Fractal
* to API Resources port so the port can prove it changed no byte. Each dataset entry is one
* scenario: a fresh deterministic world (see SnapshotWorld), one user (the server owner unless
* Golden snapshots of every Client API response that renders a resource, so a change to how
* responses are built cannot change a byte unnoticed. Each dataset entry is one scenario: a fresh deterministic world (see SnapshotWorld), one user (the server owner unless
* the scenario names another), and the list of requests whose raw responses make up its
* snapshot file. Subusers without the permissions that gate an include get their own
* scenarios, since those includes become null resources or are narrowed for them.
+2 -2
View File
@@ -208,8 +208,8 @@ arch('traits')
->expect('Pterodactyl\Traits')
->toBeTraits();
// API resources render Fractal's exact output: dropping missing values would also turn
// arrays with numeric keys into lists, so Laravel's conditional attributes are off limits.
// Dropping missing values would also turn arrays with numeric keys into lists, so Laravel's
// conditional attributes are off limits in API resources.
arch('api resources never drop missing values')
->expect('Pterodactyl\Http\Resources\Api')
->not->toUse([MissingValue::class, MergeValue::class, PotentiallyMissing::class]);
@@ -279,7 +279,7 @@ test('responses answer 200 unless the controller asks for another status', funct
test('resources nest only resources of their own api', function (): void {
expect(fn () => render(new ApplicationFixtureResource(['id' => 1]), '/?include=admin'))
->toThrow(\Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException::class);
->toThrow(\Pterodactyl\Exceptions\Resource\InvalidResourceLevelException::class);
});
test('api resources never wrap their response while wings resources keep laravel wrapping', function (): void {
@@ -5,145 +5,125 @@ declare(strict_types=1);
namespace Pterodactyl\Tests\Pest\Unit\Http\Resources\Api\Includes\IncludeSetTest;
use Illuminate\Http\Request;
use League\Fractal\Manager;
use Pterodactyl\Extensions\Spatie\Fractalistic\Fractal;
use Pterodactyl\Http\Resources\Api\Includes\IncludeSet;
use Pterodactyl\Tests\TestCase;
use Random\Engine\Mt19937;
use Random\Randomizer;
use UnexpectedValueException;
uses(TestCase::class);
/*
* IncludeSet replaces league/fractal's include parsing, so it is fuzzed against Fractal's
* Manager: random include strings built from include names, modifier syntax, empty segments
* and whitespace. Digits are left out: Fractal compares numeric names such as "1" and "01"
* loosely and IncludeSet strictly, which no real include name can tell apart.
*/
const FRAGMENTS = ['servers', 'user', 'nodes', 'a', 'b', 'limit(x|y)', ' ', '', 'x y', 'élan'];
const SEPARATORS = ['.', '.', ':', ',', '(', ')', '|', ' ', ''];
function randomInclude(Randomizer $random): string
{
$include = '';
for ($i = 0, $parts = $random->getInt(0, 6); $i < $parts; $i++) {
$include .= FRAGMENTS[$random->getInt(0, count(FRAGMENTS) - 1)].SEPARATORS[$random->getInt(0, count(SEPARATORS) - 1)];
}
return $include;
}
/** @return list<string> */
function randomIncludes(Randomizer $random): array
{
$includes = [];
for ($i = 0, $count = $random->getInt(0, 6); $i < $count; $i++) {
$includes[] = randomInclude($random);
}
return $includes;
}
/** @return list<string> */
function managerIncludes(string|array $includes, int $limit): array
{
return (new Manager)->setRecursionLimit($limit)->parseIncludes($includes)->getRequestedIncludes();
}
/**
* The Fractal container binding's request handling before IncludeSet took it over.
*
* @return list<string>
*/
function bindingNames(Request $request): array
{
return $request->collect('include')
->map(fn (mixed $value): string => is_string($value) ? $value : throw new UnexpectedValueException('The requested includes must be strings.'))
->flatMap(fn (string $value): array => explode(',', $value))
->map(fn (string $value): string => mb_trim($value))
->filter()
->values()
->all();
}
test('include lists parse like the fractal manager', function (int $limit): void {
$random = new Randomizer(new Mt19937($limit));
for ($i = 0; $i < 1500; $i++) {
$includes = randomIncludes($random);
expect(IncludeSet::parse($includes, $limit)->includes())->toBe(managerIncludes($includes, $limit), json_encode($includes, JSON_THROW_ON_ERROR));
}
})->with([1, 2, 3, 10]);
test('include strings parse like the fractal manager', function (int $limit): void {
$random = new Randomizer(new Mt19937($limit + 100));
for ($i = 0; $i < 1500; $i++) {
$include = implode(',', randomIncludes($random));
expect(IncludeSet::parse(explode(',', $include), $limit)->includes())->toBe(managerIncludes($include, $limit), $include);
}
})->with([2, 10]);
test('requests parse like the fractal binding', function (string $source): void {
$random = new Randomizer(new Mt19937(crc32($source)));
for ($i = 0; $i < 500; $i++) {
$value = $random->getInt(0, 1) === 0 ? implode(',', randomIncludes($random)) : randomIncludes($random);
$forced = $random->getInt(0, 3) === 0 ? ['password'] : [];
$request = match ($source) {
'query' => Request::create('/?'.http_build_query(['include' => $value])),
'body' => Request::create('/', 'POST', server: ['CONTENT_TYPE' => 'application/json'], content: json_encode(['include' => $value], JSON_THROW_ON_ERROR)),
};
$this->app->instance(Request::class, $request);
$fractal = $this->app->make(Fractal::class)->item(['id' => 1], fn (array $data): array => $data);
if ($forced !== []) {
$fractal->parseIncludes($forced);
}
$includes = IncludeSet::fromRequest($request, $forced);
$context = json_encode([$value, $forced], JSON_THROW_ON_ERROR);
expect($includes->requestedNames())->toBe([...bindingNames($request), ...$forced], $context)
->and($includes->includes())->toBe($fractal->createData()->getManager()->getRequestedIncludes(), $context);
}
})->with(['query', 'body']);
test('modifiers keep the include name and request their relation', function (): void {
expect(IncludeSet::parse(['servers:limit(1|0).user', 'node:sort(id|desc)'], 2)->includes())->toBe(['servers', 'servers.user', 'node']);
});
test('a falsy modifier or relation requests nothing more, as in fractal', function (array $includes): void {
expect(IncludeSet::parse($includes, 2)->includes())->toBe(managerIncludes($includes, 2));
test('include lists parse to every requested path', function (array $includes, array $limitedToTwo, array $limitedToTen): void {
expect(IncludeSet::parse($includes, 2)->includes())->toBe($limitedToTwo)
->and(IncludeSet::parse($includes)->includes())->toBe($limitedToTen);
})->with([
'zero modifier' => [['servers:0.user']],
'zero relation' => [['servers:limit.0']],
'empty relation' => [['servers:limit.']],
'empty modifier' => [['servers:.user']],
'zero name' => [['0', '0:x.user']],
'modifiers keep the name' => [
['servers:limit(1|0)', 'node:sort(id|desc)'],
['servers', 'node'],
['servers', 'node'],
],
'a modifier relation is requested' => [
['servers:limit(1|0).user', 'node:sort(id|desc)'],
['servers', 'servers.user', 'node'],
['servers', 'servers.user', 'node'],
],
'a modifier relation is cut to the limit' => [
['servers:limit(1).user.node'],
['servers', 'servers.user'],
['servers', 'servers.user', 'servers.user.node'],
],
'paths are cut to the limit' => [
['nodes.allocations.server.egg', 'egg'],
['nodes', 'nodes.allocations', 'egg'],
['nodes', 'nodes.allocations', 'nodes.allocations.server', 'nodes.allocations.server.egg', 'egg'],
],
'deep paths stop at ten segments' => [
['a.b.c.d.e.f.g.h.i.j.k.l'],
['a', 'a.b'],
['a', 'a.b', 'a.b.c', 'a.b.c.d', 'a.b.c.d.e', 'a.b.c.d.e.f', 'a.b.c.d.e.f.g', 'a.b.c.d.e.f.g.h', 'a.b.c.d.e.f.g.h.i', 'a.b.c.d.e.f.g.h.i.j'],
],
'parents are requested' => [
['servers.user.node', 'egg.nest'],
['servers', 'servers.user', 'egg', 'egg.nest'],
['servers', 'servers.user', 'servers.user.node', 'egg', 'egg.nest'],
],
'duplicates are dropped' => [
['user', 'servers.user', 'user', 'servers', 'servers.user:limit(1)', 'node:x', 'node'],
['user', 'servers', 'servers.user', 'node'],
['user', 'servers', 'servers.user', 'node'],
],
'paths that match once cut are dropped' => [
['nodes.allocations.server', 'nodes.allocations.node'],
['nodes', 'nodes.allocations'],
['nodes', 'nodes.allocations', 'nodes.allocations.server', 'nodes.allocations.node'],
],
'names are not trimmed' => [
[' servers', 'servers ', 'user . node', ''],
[' servers', 'servers ', 'user ', 'user . node', ''],
[' servers', 'servers ', 'user ', 'user . node', ''],
],
]);
test('a falsy modifier or relation requests nothing more', function (array $includes, array $expected): void {
expect(IncludeSet::parse($includes, 2)->includes())->toBe($expected);
})->with([
'zero modifier' => [['servers:0.user'], ['servers', 'servers.user']],
'zero relation' => [['servers:limit.0'], ['servers']],
'empty relation' => [['servers:limit.'], ['servers']],
'empty modifier' => [['servers:.user'], ['servers', 'servers.user']],
'zero name' => [['0', '0:x.user'], ['0']],
]);
test('numeric names are compared strictly', function (): void {
expect(IncludeSet::parse(['1', '01'])->includes())->toBe(['1', '01'])
->and(managerIncludes(['1', '01'], 10))->toBe(['1']);
expect(IncludeSet::parse(['1', '01'])->includes())->toBe(['1', '01']);
});
test('paths are cut to the recursion limit and parents are requested', function (): void {
expect(IncludeSet::parse(['nodes.allocations.server', 'egg'], 2)->includes())->toBe(['nodes', 'nodes.allocations', 'egg'])
->and(IncludeSet::parse(['nodes.allocations.server'])->includes())->toBe(['nodes', 'nodes.allocations', 'nodes.allocations.server']);
});
test('requests are read from the query string and the body', function (Request $request, array $forced, array $names, array $includes): void {
$set = IncludeSet::fromRequest($request, $forced);
test('forced includes follow the requested ones', function (): void {
$includes = IncludeSet::fromRequest(Request::create('/?include=host,%20servers.user,,'), ['password']);
expect($includes->requestedNames())->toBe(['host', 'servers.user', 'password'])
->and($includes->includes())->toBe(['host', 'servers', 'servers.user', 'password']);
});
expect($set->requestedNames())->toBe($names)
->and($set->includes())->toBe($includes);
})->with([
'a query string, with forced includes after it' => [
Request::create('/?include=host,%20servers.user,,'),
['password'],
['host', 'servers.user', 'password'],
['host', 'servers', 'servers.user', 'password'],
],
'a query list' => [
Request::create('/?include[]=host&include[]=servers.user.node,%20egg'),
[],
['host', 'servers.user.node', 'egg'],
['host', 'servers', 'servers.user', 'egg'],
],
'a json string' => [
Request::create('/', 'POST', server: ['CONTENT_TYPE' => 'application/json'], content: '{"include":"host, servers:limit(1).user"}'),
[],
['host', 'servers:limit(1).user'],
['host', 'servers', 'servers.user'],
],
'a json list, with forced includes after it' => [
Request::create('/', 'POST', server: ['CONTENT_TYPE' => 'application/json'], content: '{"include":["host","servers.user,egg"]}'),
['password'],
['host', 'servers.user', 'egg', 'password'],
['host', 'servers', 'servers.user', 'egg', 'password'],
],
'a form body' => [
Request::create('/', 'POST', ['include' => 'egg,node']),
[],
['egg', 'node'],
['egg', 'node'],
],
'the body over the query string' => [
Request::create('/?include=node', 'POST', server: ['CONTENT_TYPE' => 'application/json'], content: '{"include":"egg"}'),
[],
['egg'],
['egg'],
],
'only forced includes' => [
Request::create('/'),
['password'],
['password'],
['password'],
],
]);
test('scopes check the full path from the root', function (): void {
$root = IncludeSet::parse(['servers.user', 'node'])->root();