From 6423ef047e697260970f66932f0e95f7f7b92985 Mon Sep 17 00:00:00 2001 From: robert dennis <31261583+robertdrakedennis@users.noreply.github.com> Date: Mon, 12 Oct 2026 02:55:15 -0400 Subject: [PATCH] simpler tag sync --- app/Actions/Tags/SyncTags.php | 87 +++++++------------ .../Api/Admin/Tags/SyncTagsRequest.php | 10 +-- app/Models/Tag.php | 36 ++++---- 3 files changed, 47 insertions(+), 86 deletions(-) diff --git a/app/Actions/Tags/SyncTags.php b/app/Actions/Tags/SyncTags.php index b27710eea..7f1305759 100644 --- a/app/Actions/Tags/SyncTags.php +++ b/app/Actions/Tags/SyncTags.php @@ -4,8 +4,9 @@ declare(strict_types=1); namespace Pterodactyl\Actions\Tags; -use Illuminate\Database\Eloquent\Collection; +use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Illuminate\Database\Eloquent\Relations\MorphToMany; +use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; @@ -14,15 +15,11 @@ use Pterodactyl\Contracts\Tags\SyncsTags; use Pterodactyl\Models\Egg; use Pterodactyl\Models\Node; use Pterodactyl\Models\Tag; +use Pterodactyl\Rules\TagSlug; final readonly class SyncTags implements SyncsTags { - /** - * Rules for a tag value given as text: an existing tag's id as a numeric string, or the - * name of a tag to find or create. - * - * @var list - */ + /** @var list */ public const array TEXT = ['string', 'max:191']; /** @return NormalizedValidationRules */ @@ -30,62 +27,46 @@ final readonly class SyncTags implements SyncsTags { return [ 'tags' => ['present', 'array'], - // A numeric value is read as an existing tag id rather than a new name. - // \Pterodactyl\Rules\TagSlug is what keeps those two spaces from - // overlapping, so no rule is needed here beyond the length bound. 'tags.*' => [Rule::anyOf([['integer:strict'], self::TEXT])], ]; } - /** - * An integer id becomes the numeric string the panel sends. - * - * @param list $values - * @return list - */ - public static function values(array $values): array - { - $input = Validator::make(['tags' => $values], self::rules())->safe(); - - return array_map(fn (int|string $key): string => $input->string('tags.'.$key)->toString(), array_keys($input->array('tags'))); - } - public function syncEgg(Egg $egg, array $values): void { - $this->sync($egg, $egg->tags(), self::values($values)); + $this->sync($egg, $egg->tags(), $values); } public function syncNodeGames(Node $node, array $values): void { - $this->sync($node, $node->eggTags(), self::values($values), $node->deploymentTags()); + $this->sync($node, $node->eggTags(), $values, otherKind: $node->deploymentTags()); } public function syncNodeDeployments(Node $node, array $values): void { - $this->sync($node, $node->deploymentTags(), self::values($values), $node->eggTags()); + $this->sync($node, $node->deploymentTags(), $values, otherKind: $node->eggTags()); } /** - * A node holds each tag either as a game or as a reservation, never both, so tags - * already attached as the other kind are rejected rather than left to collide in - * the pivot table. - * * @template T of Egg|Node * * @param T $parent * @param MorphToMany $tags - * @param list $values + * @param list $values * @param MorphToMany|null $otherKind */ private function sync(Egg|Node $parent, MorphToMany $tags, array $values, ?MorphToMany $otherKind = null): void { - DB::transaction(function () use ($parent, $tags, $values, $otherKind): void { - $parent->newQuery()->lockForUpdate()->findOrFail($parent->id); - $resolved = $this->resolve($values); + /** @var array $values */ + $values = Validator::validate(['tags' => $values], self::rules())['tags']; - $taken = $otherKind?->whereKey($resolved->modelKeys())->pluck('tags.name')->implode(', ') ?? ''; - if ($taken !== '') { - throw ValidationException::withMessages(['tags' => "These tags are already on the node as the other kind: {$taken}."]); + DB::transaction(function () use ($parent, $tags, $values, $otherKind): void { + $parent->newQuery()->lockForUpdate()->findOrFail($parent->getKey()); + $resolved = $this->resolve(collect($values)); + + // A node holds each tag either as a game or as a reservation, never both. + $clashing = $otherKind?->whereKey($resolved->modelKeys())->pluck('tags.name') ?? collect(); + if ($clashing->isNotEmpty()) { + throw ValidationException::withMessages(['tags' => "These tags are already on the node as the other kind: {$clashing->implode(', ')}."]); } $tags->sync($resolved); @@ -93,31 +74,23 @@ final readonly class SyncTags implements SyncsTags } /** - * The given tags, creating a tag for each new name. This is what lets the node and egg - * tag pickers create a tag by typing its name. The slug is the typed text verbatim, so a - * name keeps its exact casing and spacing and matches a backfilled nest tag of the same - * name. + * A value that matches a tag's id or slug resolves to that tag. Any other text is the name + * of a new tag, used verbatim as its slug; a number matching no tag is a stale nest id and + * is dropped (TagSlug keeps numbers out of the slug space). * - * The values are validated first (rules() bounds each name to at most 191 characters); - * with findOrCreateFromSlugs() skipping numeric values that satisfies every rule in - * CreateTag::rules(), so tags created here need no separate check. - * - * @param list $values existing tag ids or names - * @return Collection + * @param Collection $values + * @return EloquentCollection */ - private function resolve(array $values): Collection + private function resolve(Collection $values): EloquentCollection { - $values = array_values(array_unique(array_filter(array_map(mb_trim(...), $values), fn (string $value): bool => $value !== ''))); - if ($values === []) { - return new Collection; + $values = $values->map(fn (int|string $value): string => mb_trim((string) $value))->filter(filled(...))->unique()->values(); + if ($values->isEmpty()) { + return new EloquentCollection; } - // A purely numeric value is either an existing tag id or a leftover legacy nest id, - // never a name (see TagSlug). It is resolved here if it names a real tag, and - // findOrCreateFromSlugs() never creates a tag named after a stale nest id. - $existing = Tag::matchingKeysOrSlugs($values); - $missing = array_values(array_filter($values, fn (string $value): bool => $existing->doesntContain(fn (Tag $tag): bool => $tag->slug === $value))); + $existing = Tag::matchingKeysOrSlugs($values->all()); + $newNames = $values->reject(TagSlug::isReserved(...))->diff($existing->map(fn (Tag $tag): string => $tag->slug)); - return $existing->merge(Tag::findOrCreateFromSlugs($missing)); + return $existing->merge(Tag::findOrCreateFromSlugs($newNames->all())); } } diff --git a/app/Http/Requests/Api/Admin/Tags/SyncTagsRequest.php b/app/Http/Requests/Api/Admin/Tags/SyncTagsRequest.php index 7063afffd..d31fa22e9 100644 --- a/app/Http/Requests/Api/Admin/Tags/SyncTagsRequest.php +++ b/app/Http/Requests/Api/Admin/Tags/SyncTagsRequest.php @@ -35,16 +35,10 @@ class SyncTagsRequest extends AdminApiRequest ]; } - /** - * The validated values, as strings for SyncTags. - * - * @return list - */ + /** @return list */ public function tagValues(): array { - $validated = $this->safe(); - - return array_map(fn (int|string $key): string => $validated->string('tags.'.$key)->toString(), array_keys($validated->array('tags'))); + return array_values($this->safe()->array('tags')); } /** Tag ids sent as JSON integers are read the same as the numeric strings the panel sends. */ diff --git a/app/Models/Tag.php b/app/Models/Tag.php index 4cb09c8ff..9819baa4a 100644 --- a/app/Models/Tag.php +++ b/app/Models/Tag.php @@ -48,7 +48,7 @@ class Tag extends Model } /** - * @param list $identifiers + * @param array $identifiers * @return Collection */ public static function matchingKeysOrSlugs(array $identifiers): Collection @@ -60,26 +60,24 @@ class Tag extends Model } /** - * The tags with these slugs, creating each one that does not exist yet. A built-in slug - * is created under its friendly name. A purely numeric value is never a slug (see - * TagSlug), so it is skipped rather than created. + * The tags with these slugs, creating the missing ones; a built-in slug gets its friendly + * name. Numbers are never slugs (see TagSlug), so they are skipped. * - * @param list $slugs + * @param array $slugs * @return Collection */ public static function findOrCreateFromSlugs(array $slugs): Collection { - $slugs = array_values(array_filter($slugs, fn (string $slug): bool => ! TagSlug::isReserved($slug))); - if ($slugs === []) { + $slugs = collect($slugs)->reject(TagSlug::isReserved(...))->unique(); + if ($slugs->isEmpty()) { return new Collection; } - $existing = self::query()->whereIn('slug', $slugs)->get()->keyBy('slug'); + $existing = self::query()->whereIn('slug', $slugs)->get(); - return (new Collection(array_map( - fn (string $slug): self => $existing->get($slug) ?? self::query()->firstOrCreate(['slug' => $slug], ['name' => EggSpecificTags::tryFrom($slug)?->friendlyName() ?? $slug]), - $slugs, - )))->unique(); + return $existing->merge($slugs->diff($existing->map(fn (self $tag): string => $tag->slug))->map( + fn (string $slug): self => self::query()->firstOrCreate(['slug' => $slug], ['name' => EggSpecificTags::tryFrom($slug)?->friendlyName() ?? $slug]), + )); } /** @@ -147,19 +145,15 @@ class Tag extends Model /** * @param Builder $query - * @param list $identifiers + * @param array $identifiers */ private static function filterKeysOrSlugs(Builder $query, array $identifiers): void { - $keys = array_values(array_filter($identifiers, fn (string $value): bool => preg_match('/^\d+$/', $value) === 1)); + $keys = array_values(array_filter($identifiers, TagSlug::isReserved(...))); $slugColumn = $query->getModel()->qualifyColumn('slug'); - $query->where(function (Builder $inner) use ($identifiers, $keys, $slugColumn): void { - if ($keys !== []) { - $inner->whereKey($keys); - } - - $inner->orWhereIn($slugColumn, $identifiers); - }); + $query->where(fn (Builder $inner) => $inner + ->when($keys !== [], fn (Builder $byKey) => $byKey->whereKey($keys)) + ->orWhereIn($slugColumn, $identifiers)); } }