simpler tag sync

This commit is contained in:
robert dennis
2026-10-12 05:18:59 -04:00
parent 870e00e1ca
commit 6423ef047e
3 changed files with 47 additions and 86 deletions
+30 -57
View File
@@ -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<string>
*/
/** @var list<string> */
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<mixed> $values
* @return list<string>
*/
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<Tag, T> $tags
* @param list<string> $values
* @param list<mixed> $values
* @param MorphToMany<Tag, T>|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<int|string> $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<string> $values existing tag ids or names
* @return Collection<int, Tag>
* @param Collection<array-key, int|string> $values
* @return EloquentCollection<int, Tag>
*/
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()));
}
}
@@ -35,16 +35,10 @@ class SyncTagsRequest extends AdminApiRequest
];
}
/**
* The validated values, as strings for SyncTags.
*
* @return list<string>
*/
/** @return list<mixed> */
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. */
+15 -21
View File
@@ -48,7 +48,7 @@ class Tag extends Model
}
/**
* @param list<string> $identifiers
* @param array<string> $identifiers
* @return Collection<int, self>
*/
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<string> $slugs
* @param array<string> $slugs
* @return Collection<int, self>
*/
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<self> $query
* @param list<string> $identifiers
* @param array<string> $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));
}
}