From d006674f6d76da744ff9f905da5e79cb82ffed78 Mon Sep 17 00:00:00 2001 From: robert dennis <31261583+robertdrakedennis@users.noreply.github.com> Date: Sun, 11 Oct 2026 07:15:15 -0400 Subject: [PATCH] tag actions --- app/Actions/Tags/CreateTag.php | 56 +++++++++++++- app/Actions/Tags/SyncTags.php | 53 +++++++++++-- app/Actions/Tags/UpdateTag.php | 12 +-- app/Contracts/Tags/CreatesTags.php | 6 +- app/Contracts/Tags/SyncsTags.php | 20 ++++- app/Contracts/Tags/UpdatesTags.php | 9 ++- .../Api/Admin/Tags/TagController.php | 4 +- .../Api/Admin/Tags/StoreTagRequest.php | 37 ++------- .../Api/Admin/Tags/SyncTagsRequest.php | 16 ++-- .../Api/Admin/Tags/UpdateTagRequest.php | 4 +- app/Services/Tags/TagResolutionService.php | 7 +- app/Validation/TagRules.php | 29 ------- phpstan.neon | 1 - .../Actions/Tags/CreateTagTest.php | 58 ++++++++++++++ .../Integration/Actions/Tags/SyncTagsTest.php | 76 +++++++++++++++++++ .../Actions/Tags/UpdateTagTest.php | 68 +++++++++++++++++ 16 files changed, 354 insertions(+), 102 deletions(-) delete mode 100644 app/Validation/TagRules.php create mode 100644 tests/Integration/Actions/Tags/CreateTagTest.php create mode 100644 tests/Integration/Actions/Tags/SyncTagsTest.php create mode 100644 tests/Integration/Actions/Tags/UpdateTagTest.php diff --git a/app/Actions/Tags/CreateTag.php b/app/Actions/Tags/CreateTag.php index 6dd8febb7..1a4181afe 100644 --- a/app/Actions/Tags/CreateTag.php +++ b/app/Actions/Tags/CreateTag.php @@ -4,18 +4,66 @@ declare(strict_types=1); namespace Pterodactyl\Actions\Tags; +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; use Pterodactyl\Contracts\Tags\CreatesTags; use Pterodactyl\Models\Tag; +use Pterodactyl\Rules\TagSlug; final readonly class CreateTag implements CreatesTags { /** - * Create a new tag from validated attributes. + * A tag's fields. Pass the tag being edited so its own slug does not collide with the + * uniqueness check. A slug may not be purely numeric, so a leftover legacy nest id can be + * told apart from a real tag and a slug can never shadow a tag id (see TagSlug). * - * @param TagData $data + * @return NormalizedValidationRules */ - public function create(array $data): Tag + public static function rules(?Tag $tag = null): array { - return Tag::query()->create($data); + return [ + 'name' => ['required', 'string', 'between:1,191'], + 'slug' => ['required', 'string', 'between:1,191', Rule::unique('tags', 'slug')->ignore($tag), new TagSlug], + // Custom tags store an optional chip colour; built-in tags ignore it - their + // colour is owned by EggSpecificTags. Null clears it. + 'color' => ['nullable', 'string', 'hex_color'], + 'legacy_nest_id' => ['sometimes', 'nullable', 'integer'], + ]; + } + + /** + * Validates tag input and returns the model attributes it describes. The colour and legacy + * nest id are left out when they are not given, so an edited tag keeps its stored values; + * a blank colour is cleared. + * + * @param ActionInput $input + * @return array{name: string, slug: string, color?: string|null, legacy_nest_id?: int|null} + */ + public static function attributes(array $input, ?Tag $tag = null): array + { + $input = Validator::make($input, self::rules($tag))->safe(); + + $attributes = [ + 'name' => $input->string('name')->toString(), + 'slug' => $input->string('slug')->toString(), + ]; + + if ($input->has('color')) { + $attributes['color'] = $input->filled('color') ? $input->string('color')->toString() : null; + } + + if ($input->has('legacy_nest_id')) { + $attributes['legacy_nest_id'] = $input->filled('legacy_nest_id') ? $input->integer('legacy_nest_id') : null; + } + + return $attributes; + } + + /** + * @param ActionInput $input + */ + public function create(array $input): Tag + { + return Tag::query()->create(self::attributes($input)); } } diff --git a/app/Actions/Tags/SyncTags.php b/app/Actions/Tags/SyncTags.php index a7a41e9f1..698e868e9 100644 --- a/app/Actions/Tags/SyncTags.php +++ b/app/Actions/Tags/SyncTags.php @@ -6,6 +6,8 @@ namespace Pterodactyl\Actions\Tags; use Illuminate\Database\Eloquent\Relations\MorphToMany; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; use Illuminate\Validation\ValidationException; use Pterodactyl\Contracts\Tags\SyncsTags; use Pterodactyl\Models\Egg; @@ -15,24 +17,63 @@ use Pterodactyl\Services\Tags\TagResolutionService; 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 + */ + public const array TEXT = ['string', 'max:191']; + public function __construct(private TagResolutionService $resolver) {} - /** @param list $values */ + /** + * The tags to sync, each an existing tag's id or a new tag's name. An id may also be an + * integer. + * + * @return NormalizedValidationRules + */ + public static function rules(): array + { + 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])], + ]; + } + + /** + * Validates tag values under `tags` and returns them as strings for the resolver, an + * integer id becoming 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'))); + } + + /** @param list $values */ public function syncEgg(Egg $egg, array $values): void { - $this->sync($egg, $egg->tags(), $values); + $this->sync($egg, $egg->tags(), self::values($values)); } - /** @param list $values */ + /** @param list $values */ public function syncNodeGames(Node $node, array $values): void { - $this->sync($node, $node->eggTags(), $values, $node->deploymentTags()); + $this->sync($node, $node->eggTags(), self::values($values), $node->deploymentTags()); } - /** @param list $values */ + /** @param list $values */ public function syncNodeDeployments(Node $node, array $values): void { - $this->sync($node, $node->deploymentTags(), $values, $node->eggTags()); + $this->sync($node, $node->deploymentTags(), self::values($values), $node->eggTags()); } /** diff --git a/app/Actions/Tags/UpdateTag.php b/app/Actions/Tags/UpdateTag.php index e538b4bb2..d78031adc 100644 --- a/app/Actions/Tags/UpdateTag.php +++ b/app/Actions/Tags/UpdateTag.php @@ -12,19 +12,19 @@ use Pterodactyl\Models\Tag; final readonly class UpdateTag implements UpdatesTags { /** - * Update an existing tag from validated attributes. A built-in game tag's slug is - * the key feature gating matches on and its presentation comes from the - * EggSpecificTags enum, so it must never be renamed or relabelled. + * Update an existing tag. A built-in game tag's slug is the key feature gating matches on + * and its presentation comes from the EggSpecificTags enum, so it must never be renamed or + * relabelled. * - * @param TagData $data + * @param ActionInput $input * * @throws DisplayException */ - public function update(Tag $tag, array $data): Tag + public function update(Tag $tag, array $input): Tag { throw_if(EggSpecificTags::isSpecial($tag->slug), DisplayException::class, 'Built-in game tags cannot be edited.'); - $tag->update($data); + $tag->update(CreateTag::attributes($input, $tag)); return $tag; } diff --git a/app/Contracts/Tags/CreatesTags.php b/app/Contracts/Tags/CreatesTags.php index 9d5015003..2feebf0ea 100644 --- a/app/Contracts/Tags/CreatesTags.php +++ b/app/Contracts/Tags/CreatesTags.php @@ -9,9 +9,9 @@ use Pterodactyl\Models\Tag; interface CreatesTags { /** - * Create a new tag from validated attributes. + * Create a new tag. The input is validated here, so it can come straight from any caller. * - * @param TagData $data + * @param ActionInput $input name and slug, and optionally color and legacy_nest_id */ - public function create(array $data): Tag; + public function create(array $input): Tag; } diff --git a/app/Contracts/Tags/SyncsTags.php b/app/Contracts/Tags/SyncsTags.php index 25f0f4a2d..f2dde92da 100644 --- a/app/Contracts/Tags/SyncsTags.php +++ b/app/Contracts/Tags/SyncsTags.php @@ -7,14 +7,28 @@ namespace Pterodactyl\Contracts\Tags; use Pterodactyl\Models\Egg; use Pterodactyl\Models\Node; +/** + * Replaces the full set of tags of one kind on an egg or a node. Each value is an existing + * tag's id, as an integer or a numeric string, or the name of a tag to find or create. The + * values are validated here, so they can come straight from any caller; errors are reported + * under `tags` and `tags.N`. + */ interface SyncsTags { - /** @param list $values */ + /** @param list $values */ public function syncEgg(Egg $egg, array $values): void; - /** @param list $values */ + /** + * Replace the games a node accepts. A tag the node holds as a reservation is refused. + * + * @param list $values + */ public function syncNodeGames(Node $node, array $values): void; - /** @param list $values */ + /** + * Replace the reservations on a node. A tag the node accepts as a game is refused. + * + * @param list $values + */ public function syncNodeDeployments(Node $node, array $values): void; } diff --git a/app/Contracts/Tags/UpdatesTags.php b/app/Contracts/Tags/UpdatesTags.php index a4528d135..918fc2d98 100644 --- a/app/Contracts/Tags/UpdatesTags.php +++ b/app/Contracts/Tags/UpdatesTags.php @@ -10,11 +10,14 @@ use Pterodactyl\Models\Tag; interface UpdatesTags { /** - * Update an existing tag from validated attributes. Built-in game tags cannot be edited. + * Update an existing tag. Built-in game tags cannot be edited. The input is validated here, + * so it can come straight from any caller. It takes the fields a tag is created with, + * required ones included; the colour and legacy nest id keep their stored values when they + * are left out. * - * @param TagData $data + * @param ActionInput $input the fields a tag is created with * * @throws DisplayException */ - public function update(Tag $tag, array $data): Tag; + public function update(Tag $tag, array $input): Tag; } diff --git a/app/Http/Controllers/Api/Admin/Tags/TagController.php b/app/Http/Controllers/Api/Admin/Tags/TagController.php index 2e87d8fd6..94ccf6e97 100644 --- a/app/Http/Controllers/Api/Admin/Tags/TagController.php +++ b/app/Http/Controllers/Api/Admin/Tags/TagController.php @@ -97,7 +97,7 @@ class TagController extends AdminApiController #[ResponseFromTransformer(TagTransformer::class, Tag::class, status: 201, description: 'Tag created.', resourceKey: 'tag', meta: ['resource' => 'https://panel.example.com/api/admin/tags/1'])] public function store(StoreTagRequest $request, CreatesTags $tags): JsonResponse { - $tag = $tags->create($request->payload()); + $tag = $tags->create($request->actionInput()); Activity::event('admin:tag.create') ->subject($tag) @@ -127,7 +127,7 @@ class TagController extends AdminApiController #[ScribeResponse(self::BUILT_IN_ERROR, status: 400, description: 'The tag is a built-in game tag.')] public function update(UpdateTagRequest $request, UpdatesTags $tags, Tag $tag): array { - $tag = $tags->update($tag, $request->payload()); + $tag = $tags->update($tag, $request->actionInput()); Activity::event('admin:tag.update') ->subject($tag) diff --git a/app/Http/Requests/Api/Admin/Tags/StoreTagRequest.php b/app/Http/Requests/Api/Admin/Tags/StoreTagRequest.php index b1c625003..22e614c3e 100644 --- a/app/Http/Requests/Api/Admin/Tags/StoreTagRequest.php +++ b/app/Http/Requests/Api/Admin/Tags/StoreTagRequest.php @@ -4,12 +4,10 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Api\Admin\Tags; +use Pterodactyl\Actions\Tags\CreateTag; use Pterodactyl\Enum\Permissions; use Pterodactyl\Http\Requests\Api\Admin\AdminApiRequest; -use Pterodactyl\Rules\TagSlug; -use Pterodactyl\Support\JsonValueGuard; use Pterodactyl\Support\ValidationRuleSubset; -use Pterodactyl\Validation\TagRules; class StoreTagRequest extends AdminApiRequest { @@ -23,42 +21,17 @@ class StoreTagRequest extends AdminApiRequest */ public function rules(): array { - return $this->withSlugRule(TagRules::rules()); + return $this->writable(CreateTag::rules()); } /** - * Model attributes for the tag. The color stays absent when the request - * omits it so an update leaves the stored value alone. - * - * @return TagData - */ - public function payload(): array - { - $payload = [ - 'name' => $this->string('name')->toString(), - 'slug' => $this->string('slug')->toString(), - ]; - - if ($this->exists('color')) { - $payload['color'] = JsonValueGuard::nullableString($this->input('color')); - } - - return $payload; - } - - /** - * Narrow the model rules to the writable fields and forbid numeric slugs, so a - * leftover legacy nest id can be told apart from a real tag and a slug can never - * shadow a tag id (see TagSlug). + * Narrow a tag's rules to the fields the API writes; it never sets the legacy nest id. * * @param NormalizedValidationRules $rules * @return NormalizedValidationRules */ - protected function withSlugRule(array $rules): array + protected function writable(array $rules): array { - $rules = ValidationRuleSubset::select($rules, ['name', 'slug', 'color']); - $rules['slug'] = array_merge($rules['slug'], [new TagSlug]); - - return $rules; + return ValidationRuleSubset::select($rules, ['name', 'slug', 'color']); } } diff --git a/app/Http/Requests/Api/Admin/Tags/SyncTagsRequest.php b/app/Http/Requests/Api/Admin/Tags/SyncTagsRequest.php index 346d316c7..60d880336 100644 --- a/app/Http/Requests/Api/Admin/Tags/SyncTagsRequest.php +++ b/app/Http/Requests/Api/Admin/Tags/SyncTagsRequest.php @@ -4,10 +4,10 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Api\Admin\Tags; +use Pterodactyl\Actions\Tags\SyncTags; use Pterodactyl\Enum\Permissions; use Pterodactyl\Http\Requests\Api\Admin\AdminApiRequest; use Pterodactyl\Services\Tags\TagResolutionService; -use Pterodactyl\Support\JsonValueGuard; /** * Replace the full set of tags on an egg or a node. @@ -24,16 +24,16 @@ class SyncTagsRequest extends AdminApiRequest } /** + * The action's rules, with every value held to its text rules: integer ids are numeric + * strings by now (see prepareForValidation()). + * * @return ValidationRules */ public function rules(): array { 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.*' => ['string', 'max:191'], + 'tags' => SyncTags::rules()['tags'], + 'tags.*' => SyncTags::TEXT, ]; } @@ -44,7 +44,9 @@ class SyncTagsRequest extends AdminApiRequest */ public function tagValues(): array { - return JsonValueGuard::stringList(array_values(JsonValueGuard::jsonArray($this->validated('tags', [])))); + $validated = $this->safe(); + + return array_map(fn (int|string $key): string => $validated->string('tags.'.$key)->toString(), array_keys($validated->array('tags'))); } /** Tag ids sent as JSON integers are read the same as the numeric strings the panel sends. */ diff --git a/app/Http/Requests/Api/Admin/Tags/UpdateTagRequest.php b/app/Http/Requests/Api/Admin/Tags/UpdateTagRequest.php index 7635af3ea..c5df8711b 100644 --- a/app/Http/Requests/Api/Admin/Tags/UpdateTagRequest.php +++ b/app/Http/Requests/Api/Admin/Tags/UpdateTagRequest.php @@ -4,9 +4,9 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Api\Admin\Tags; +use Pterodactyl\Actions\Tags\CreateTag; use Pterodactyl\Enum\Permissions; use Pterodactyl\Models\Tag; -use Pterodactyl\Validation\TagRules; class UpdateTagRequest extends StoreTagRequest { @@ -20,6 +20,6 @@ class UpdateTagRequest extends StoreTagRequest */ public function rules(): array { - return $this->withSlugRule(TagRules::rules($this->parameter('tag', Tag::class))); + return $this->writable(CreateTag::rules($this->parameter('tag', Tag::class))); } } diff --git a/app/Services/Tags/TagResolutionService.php b/app/Services/Tags/TagResolutionService.php index b50136882..3affc45e1 100644 --- a/app/Services/Tags/TagResolutionService.php +++ b/app/Services/Tags/TagResolutionService.php @@ -15,10 +15,9 @@ class TagResolutionService * any tag that does not exist yet. This is what lets the node and egg tag * pickers create a tag inline by typing a new name. * - * Callers validate the submitted values first (SyncTagsRequest bounds each entry - * to a string of at most 191 characters); combined with the numeric guard below - * that satisfies every rule in TagRules::rules(), so tags created here need no - * separate check. + * SyncTags validates the values first (it bounds each name to at most 191 + * characters); combined with the numeric guard below that satisfies every rule + * in CreateTag::rules(), so tags created here need no separate check. * * @param string[] $values * @return int[] diff --git a/app/Validation/TagRules.php b/app/Validation/TagRules.php deleted file mode 100644 index 740595c4e..000000000 --- a/app/Validation/TagRules.php +++ /dev/null @@ -1,29 +0,0 @@ - ['required', 'string', 'between:1,191'], - 'slug' => ['required', 'string', 'between:1,191', Rule::unique('tags', 'slug')->ignore($ignore)], - // Custom tags store an optional chip colour; built-in tags ignore it - their - // colour is owned by EggSpecificTags. Null clears it. - 'color' => ['nullable', 'string', 'hex_color'], - 'legacy_nest_id' => ['sometimes', 'nullable', 'integer'], - ]; - } -} diff --git a/phpstan.neon b/phpstan.neon index f2cb16da6..6b73e96ef 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -89,7 +89,6 @@ parameters: DatabaseHostUpdateData: 'array{name: string, host: string, port: int, username: string, password?: string|null, node_id: int|null, extensions?: \Pterodactyl\Services\Extensions\ValidatedExtensionValues}' EggVariableData: 'array{name: string, description: string, env_variable: string, default_value: string, user_viewable: bool, user_editable: bool, rules: string}' MultipartUploadPart: 'array{etag: string, part_number: int}' - TagData: 'array{name: string, slug: string, color?: string|null}' ApiKeyUpdateData: 'array{memo: string|null}' SftpAuthenticationData: 'array{type: string|null, username: string, password: string}' EggCreationData: 'array{name: string, description: string|null, docker_images: array, force_outgoing_ip: bool, features: list, startup: string, file_denylist?: list, config_from?: int|null, config_stop?: string|null, config_startup?: string|null, config_logs?: string|null, config_files?: string|null, extensions?: \Pterodactyl\Services\Extensions\ValidatedExtensionValues}' diff --git a/tests/Integration/Actions/Tags/CreateTagTest.php b/tests/Integration/Actions/Tags/CreateTagTest.php new file mode 100644 index 000000000..570c5bec4 --- /dev/null +++ b/tests/Integration/Actions/Tags/CreateTagTest.php @@ -0,0 +1,58 @@ + */ +function tag(array $overrides = []): array +{ + return [...['name' => 'Direct', 'slug' => 'direct-tag'], ...$overrides]; +} + +test('tags created without the http api meet the same rules', function (array $input, string $field): void { + Tag::factory()->create(['slug' => 'taken']); + $count = Tag::query()->count(); + + try { + $this->app->make(CreatesTags::class)->create(tag($input)); + $this->fail('The tag was created.'); + } catch (ValidationException $validationException) { + expect(array_keys($validationException->errors()))->toBe([$field]); + } + + expect(Tag::query()->count())->toBe($count); +})->with([ + 'a missing name' => [['name' => null], 'name'], + 'a name that is too long' => [['name' => str_repeat('a', 192)], 'name'], + 'a missing slug' => [['slug' => null], 'slug'], + 'a taken slug' => [['slug' => 'taken'], 'slug'], + 'a purely numeric slug' => [['slug' => '42'], 'slug'], + 'a colour that is not hex' => [['color' => 'red'], 'color'], + 'a legacy nest id that is not a number' => [['legacy_nest_id' => 'one'], 'legacy_nest_id'], +]); + +test('values are coerced the way laravel validates them', function (int|string $legacyNestId): void { + $tag = $this->app->make(CreatesTags::class)->create(tag(['color' => '#a1b2c3', 'legacy_nest_id' => $legacyNestId])); + + $tag->refresh(); + expect($tag->name)->toBe('Direct') + ->and($tag->slug)->toBe('direct-tag') + ->and($tag->color)->toBe('#a1b2c3') + ->and($tag->legacy_nest_id)->toBe(7); +})->with([[7], ['7']]); + +test('a tag given no colour or a blank one has none', function (?string $color): void { + $tag = $this->app->make(CreatesTags::class)->create(tag($color === null ? [] : ['color' => $color])); + + expect($tag->refresh()->color)->toBeNull() + ->and($tag->legacy_nest_id)->toBeNull(); +})->with([[null], ['']]); diff --git a/tests/Integration/Actions/Tags/SyncTagsTest.php b/tests/Integration/Actions/Tags/SyncTagsTest.php new file mode 100644 index 000000000..f80e921b9 --- /dev/null +++ b/tests/Integration/Actions/Tags/SyncTagsTest.php @@ -0,0 +1,76 @@ +create(); + $count = Tag::query()->count(); + + try { + $this->app->make(SyncsTags::class)->syncEgg($egg, $values); + $this->fail('The tags were synced.'); + } catch (ValidationException $validationException) { + expect(array_keys($validationException->errors()))->toBe([$field]); + } + + expect($egg->tags()->exists())->toBeFalse() + ->and(Tag::query()->count())->toBe($count); +})->with([ + 'a name that is too long' => [[str_repeat('a', 192)], 'tags.0'], + 'a boolean' => [['fresh-name', true], 'tags.1'], + 'null' => [[null], 'tags.0'], + 'a float' => [[1.5], 'tags.0'], + 'a list' => [[['nested']], 'tags.0'], +]); + +test('integer ids, numeric strings and names all resolve to tags', function (): void { + $first = Tag::factory()->create(); + $second = Tag::factory()->create(); + $egg = Egg::factory()->create(); + + // A numeric value that names no tag is a stale legacy nest id, and is dropped. + $this->app->make(SyncsTags::class)->syncEgg($egg, [$first->id, (string) $second->id, ' Brand New ', '999999']); + + $created = Tag::query()->where('slug', 'Brand New')->sole(); + expect($egg->tags()->pluck('tags.id')->sort()->values()->all())->toBe([$first->id, $second->id, $created->id]) + ->and(Tag::query()->where('slug', '999999')->exists())->toBeFalse(); +}); + +test('an empty list clears the tags', function (): void { + $egg = Egg::factory()->create(); + $egg->tags()->attach(Tag::factory()->create()); + + $this->app->make(SyncsTags::class)->syncEgg($egg, []); + + expect($egg->tags()->exists())->toBeFalse(); +}); + +test('a node synced directly still cannot hold a tag as both kinds', function (): void { + $tag = Tag::factory()->create(['name' => 'Both Kinds']); + $node = Node::factory()->withLocation()->create(); + $sync = $this->app->make(SyncsTags::class); + + $sync->syncNodeGames($node, [$tag->id]); + + try { + $sync->syncNodeDeployments($node, [$tag->id]); + $this->fail('The tag was synced as both kinds.'); + } catch (ValidationException $validationException) { + expect($validationException->errors())->toBe(['tags' => ['These tags are already on the node as the other kind: Both Kinds.']]); + } + + expect($node->eggTags()->pluck('tags.id')->all())->toBe([$tag->id]) + ->and($node->deploymentTags()->exists())->toBeFalse(); +}); diff --git a/tests/Integration/Actions/Tags/UpdateTagTest.php b/tests/Integration/Actions/Tags/UpdateTagTest.php new file mode 100644 index 000000000..1966d614a --- /dev/null +++ b/tests/Integration/Actions/Tags/UpdateTagTest.php @@ -0,0 +1,68 @@ +create(['color' => '#123456', 'legacy_nest_id' => 3]); + + $this->app->make(UpdatesTags::class)->update($tag, ['name' => 'Renamed', 'slug' => 'renamed']); + + $tag->refresh(); + expect($tag->name)->toBe('Renamed') + ->and($tag->slug)->toBe('renamed') + ->and($tag->color)->toBe('#123456') + ->and($tag->legacy_nest_id)->toBe(3); +}); + +test('a tag keeps its own slug, and a null colour clears it', function (): void { + $tag = Tag::factory()->create(['slug' => 'mine', 'color' => '#123456']); + + $this->app->make(UpdatesTags::class)->update($tag, ['name' => 'Mine', 'slug' => 'mine', 'color' => null, 'legacy_nest_id' => '12']); + + $tag->refresh(); + expect($tag->slug)->toBe('mine') + ->and($tag->color)->toBeNull() + ->and($tag->legacy_nest_id)->toBe(12); +}); + +test('tags updated without the http api meet the same rules', function (array $input, string $field): void { + Tag::factory()->create(['slug' => 'taken']); + $tag = Tag::factory()->create()->refresh(); + $before = $tag->getAttributes(); + + try { + $this->app->make(UpdatesTags::class)->update($tag, [...['name' => $tag->name, 'slug' => $tag->slug], ...$input]); + $this->fail('The tag was updated.'); + } catch (ValidationException $validationException) { + expect(array_keys($validationException->errors()))->toBe([$field]); + } + + expect($tag->fresh()->getAttributes())->toBe($before); +})->with([ + 'a blank name' => [['name' => ''], 'name'], + 'a taken slug' => [['slug' => 'taken'], 'slug'], + 'a purely numeric slug' => [['slug' => '7'], 'slug'], + 'a colour that is not hex' => [['color' => '#12345g'], 'color'], +]); + +test('built-in game tags cannot be edited, whatever the input', function (array $input): void { + $tag = Tag::factory()->predefined()->create(); + + expect(fn () => $this->app->make(UpdatesTags::class)->update($tag, $input)) + ->toThrow(DisplayException::class, 'Built-in game tags cannot be edited.'); + expect($tag->fresh()->slug)->toBe('minecraft'); +})->with([ + 'valid input' => [['name' => 'Changed', 'slug' => 'changed']], + 'invalid input' => [[]], +]);