|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace App\GraphQL\Mutations; |
| 6 | + |
| 7 | +use App\Models\PinnedTestMeasurement; |
| 8 | +use App\Models\Project; |
| 9 | +use Exception; |
| 10 | +use Illuminate\Support\Collection; |
| 11 | +use Illuminate\Support\Facades\Gate; |
| 12 | + |
| 13 | +final class UpdatePinnedTestMeasurementOrder extends AbstractMutation |
| 14 | +{ |
| 15 | + /** @var ?Collection<PinnedTestMeasurement> */ |
| 16 | + public ?Collection $pinnedTestMeasurements = null; |
| 17 | + |
| 18 | + /** |
| 19 | + * @param array{ |
| 20 | + * projectId: int, |
| 21 | + * pinnedTestMeasurementIds: array<int>, |
| 22 | + * } $args |
| 23 | + */ |
| 24 | + protected function mutate(array $args): void |
| 25 | + { |
| 26 | + $project = Project::find((int) $args['projectId']); |
| 27 | + Gate::authorize('updatePinnedTestMeasurementOrder', $project); |
| 28 | + |
| 29 | + $projectMeasurementIds = $project?->pinnedTestMeasurements()->pluck('id'); |
| 30 | + $newOrder = collect($args['pinnedTestMeasurementIds']); |
| 31 | + |
| 32 | + if ($projectMeasurementIds->diff($newOrder)->isNotEmpty()) { |
| 33 | + throw new Exception('IDs for all PinnedTestMeasurements must be provided.'); |
| 34 | + } |
| 35 | + |
| 36 | + if ($newOrder->count() !== $projectMeasurementIds->count()) { |
| 37 | + throw new Exception('Provided set cannot contain duplicate IDs.'); |
| 38 | + } |
| 39 | + |
| 40 | + if ($newOrder->isEmpty()) { |
| 41 | + throw new Exception("Can't order an empty set."); |
| 42 | + } |
| 43 | + |
| 44 | + // We start at the previous maximum ID + 1 to guarantee that there are never any conflicts. |
| 45 | + // Only the relative order matters, so we don't care if the minimum position is now 1. |
| 46 | + $position = (int) $project?->pinnedTestMeasurements()->max('position') + 1; |
| 47 | + foreach ($newOrder as $id) { |
| 48 | + /** @var PinnedTestMeasurement $measurement */ |
| 49 | + $measurement = $project?->pinnedTestMeasurements()->findOrFail((int) $id); |
| 50 | + |
| 51 | + $measurement->position = $position; |
| 52 | + $measurement->save(); |
| 53 | + $position++; |
| 54 | + } |
| 55 | + |
| 56 | + $this->pinnedTestMeasurements = $project?->pinnedTestMeasurements()->orderBy('position')->get(); |
| 57 | + } |
| 58 | +} |
0 commit comments