Files
projectsend/app/Support/Concerns/HasUniqueSlug.php
ignacionelson 98597d462d Give a deleted folder's name back
Delete a folder called Test and you could never have a folder called Test
again. The deletion worked, the folder left the screen, and the name went
with it — permanently, with an error that named a collision against a row
the interface will not show you and offered nothing to do about it.

Files and groups had it too. All three carry a unique index on slug and
all three soft-delete, so the trashed row sat in the index holding a name
nothing could reach. A public one failed outright at the validator, which
checks the table and therefore sees rows the screen does not. A private
one failed more quietly: the derived slug stepped around the trashed row
into report-2, then report-3, once per deletion, climbing forever.

The reservation was deliberate — a trashed row's slug was kept so that
restoring it could not land on somebody else's URL. But nothing in this
application restores anything. There is no restore() call, no route, no
screen; File's own comment says as much. Soft deletes are here so rows can
outlive their delete for foreign keys, the activity log and the erasure
grace period, never so they can come back. The slug was being held for a
page that could not return, and route binding already 404s the trashed row
in the meantime.

So deleting now hands the slug back, and the database is what makes that a
rewrite rather than a gentler lookup: teaching the collision checks to skip
trashed rows would leave two rows holding "report", which the unique index
rejects whatever the application thinks. The slug moves to report__deleted-42
instead. Underscores are the whole trick — Str::slug() turns them into
hyphens and Rules::slug() refuses them outright, so no derived slug and no
hand-typed one can ever land on a vacated one. That is a guarantee about
the character class rather than a hope about collisions.

The format lives in VacatedSlug rather than on the trait because the
migration needs it too and a trait constant cannot be reached through the
trait's own name — the first version of this was a fatal error waiting for
whoever ran migrations. The migration matters as much as the hook: without
it the fix only helps installations that have never deleted anything, and
every name already buried stays buried.

The collision checks still count trashed rows. It costs nothing and keeps
them honest about what the index will accept if a row is ever soft-deleted
by something that bypasses model events.

previous_file_id had this same bug and was fixed this same way, in
File::detachOnDelete — a trashed row holding its predecessor's unique slot
so the chain could never be re-linked. This is that fix, for the other four
unique indexes' worth of the same mistake. users.email is the one left, and
is deliberately not in here: an email address is a login identity rather
than a URL handle, and freeing it silently is the wrong answer.

Fixes #1645

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-18 12:11:02 -03:00

128 lines
4.7 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Support\Concerns;
use App\Support\VacatedSlug;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
/**
* Derives a URL slug from the model's name on create, and keeps it unique.
*
* The public URL of a file, folder or group needs a slug, but plenty of call
* sites (tests, seeders, the upload flow, FolderService, the v1 importer)
* create one without going through a form that requires it — so fall back to
* deriving one from the name rather than failing at the database.
*
* Deleting a row hands its slug back. A soft-deleted row is unreachable —
* every public lookup goes through Eloquent, so the soft-delete scope has
* already excluded it — and nothing in the application can restore one, so
* a slug it kept holding would be reserved for a page that can never return.
* Holding one is what burned the name of any deleted folder for good: the
* unique index still saw the row, so the name could never be used again and
* the screen could not say why, because the row it collided with is one the
* interface will not show.
*
* The database is what forces the vacating to be a rewrite rather than a
* softer lookup. Teaching the collision checks to ignore trashed rows is not
* enough on its own — two rows would then both hold `report`, and the unique
* index rejects that however the application feels about it. So the slug
* moves into a namespace nothing else can occupy: `report__deleted-42`.
* Underscores are the whole trick. Str::slug() turns them into hyphens and
* Rules::slug() refuses them outright, so neither a derived slug nor a
* hand-typed one can ever land on a vacated slug, whatever the row is called.
*
* The collision checks still count trashed rows anyway. It costs nothing, and
* it keeps them honest about what the index will actually accept if a row is
* ever soft-deleted by something that bypasses model events.
*
* Requires SoftDeletes: the collision check reaches for withTrashed(), and
* vacating is only meaningful for a row that outlives its own delete.
*
* @phpstan-require-extends Model
*/
trait HasUniqueSlug
{
/**
* Booted by Eloquent alongside — not instead of — the model's own
* booted(), which several of these models use for unrelated hooks.
*/
protected static function bootHasUniqueSlug(): void
{
static::creating(function (self $model): void {
if (blank($model->slug)) {
$model->slug = static::uniqueSlugFrom($model->name);
}
});
static::deleted(function (self $model): void {
static::vacateSlug($model);
});
}
/**
* @param int|null $ignoreId the row being renamed, which must not
* collide with the slug it already holds
*/
public static function uniqueSlugFrom(string $name, ?int $ignoreId = null): string
{
$base = Str::slug($name) ?: static::slugFallback();
$slug = $base;
$suffix = 2;
$collides = fn (string $candidate): bool => static::query()->withTrashed()
->where('slug', $candidate)
->when($ignoreId !== null, fn (Builder $query) => $query->whereKeyNot($ignoreId))
->exists();
while ($collides($slug)) {
$slug = $base.'-'.$suffix;
$suffix++;
}
return $slug;
}
/**
* Hands a soft-deleted row's slug back to the names still in use.
*
* Written through the query builder on purpose: this is bookkeeping, not
* an edit somebody made, so it must not move updated_at or fire a second
* round of model events on a row that is already on its way out.
*/
protected static function vacateSlug(self $model): void
{
// A row that is really gone took its slug with it. `deleted` fires
// for forceDelete() too, and there is nothing left to rewrite.
if ($model->isForceDeleting()) {
return;
}
if (blank($model->slug)) {
return;
}
$vacated = VacatedSlug::for($model->slug, $model->getKey());
if ($vacated === $model->slug) {
return;
}
static::query()->withTrashed()->whereKey($model->getKey())->toBase()->update(['slug' => $vacated]);
// Keep the in-memory row telling the truth for whatever the caller
// does with it after the delete returns.
$model->slug = $vacated;
$model->syncOriginalAttribute('slug');
}
/**
* Stands in when the name slugs to nothing at all — a name of only
* punctuation or of characters Str::slug() drops entirely.
*/
abstract protected static function slugFallback(): string;
}