Skip to content

Commit

Permalink
support reorder from any key
Browse files Browse the repository at this point in the history
  • Loading branch information
QuentinGab committed Jan 10, 2024
1 parent 41cfb7d commit a4eba97
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 6 deletions.
11 changes: 5 additions & 6 deletions src/Models/Media.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<int, Media> */
$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;
Expand Down
36 changes: 36 additions & 0 deletions tests/Feature/MediaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');

});

0 comments on commit a4eba97

Please sign in to comment.