From a4eba97966966d8785cb46f0af69cf45eaa94e1a Mon Sep 17 00:00:00 2001 From: Quentin Gabriele Date: Wed, 10 Jan 2024 13:00:51 +0100 Subject: [PATCH] support reorder from any key --- src/Models/Media.php | 11 +++++------ tests/Feature/MediaTest.php | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/src/Models/Media.php b/src/Models/Media.php index 81c01ce..f6eabc4 100644 --- a/src/Models/Media.php +++ b/src/Models/Media.php @@ -408,18 +408,17 @@ public function getSrcset(): Collection } /** - * @param null|(Closure(string $previous): string) $sequence - * @param null|(Closure(string $previous): string) $sequence + * @param null|(Closure(null|string $previous): string) $sequence */ - public static function reorder(array $ids, ?Closure $sequence = null): void + public static function reorder(array $keys, ?Closure $sequence = null, string $using = 'id'): void { /** @var EloquentCollection */ $models = static::query() - ->whereIn('id', $ids) + ->whereIn($using, $keys) ->get(); - $models = $models->sortBy(function (Media $model) use ($ids) { - return array_search($model->getKey(), $ids); + $models = $models->sortBy(function (Media $model) use ($keys, $using) { + return array_search($model->{$using}, $keys); }); $previous = $sequence ? null : -1; diff --git a/tests/Feature/MediaTest.php b/tests/Feature/MediaTest.php index 4b783bb..1b566df 100644 --- a/tests/Feature/MediaTest.php +++ b/tests/Feature/MediaTest.php @@ -401,3 +401,39 @@ expect($second_media->refresh()->order)->toBe('2'); }); + +it('reorder models using uuids', function () { + + $first_media = MediaFactory::new()->create(['order' => '0']); + $second_media = MediaFactory::new()->create(['order' => '1']); + $third_media = MediaFactory::new()->create(['order' => '2']); + + Media::reorder([ + $third_media->uuid, + $first_media->uuid, + $second_media->uuid, + ], using: 'uuid'); + + expect($third_media->refresh()->order)->toBe('0'); + expect($first_media->refresh()->order)->toBe('1'); + expect($second_media->refresh()->order)->toBe('2'); + +}); + +it('reorder models from a custom sequence', function () { + + $first_media = MediaFactory::new()->create(['order' => '0']); + $second_media = MediaFactory::new()->create(['order' => '1']); + $third_media = MediaFactory::new()->create(['order' => '2']); + + Media::reorder([ + $third_media->getKey(), + $first_media->getKey(), + $second_media->getKey(), + ], sequence: fn (?string $previous) => (string) ($previous === null ? 0 : (intval($previous) + 2))); + + expect($third_media->refresh()->order)->toBe('0'); + expect($first_media->refresh()->order)->toBe('2'); + expect($second_media->refresh()->order)->toBe('4'); + +});