$data validated input * @param list $photos freshly uploaded files * @param list|null $expected the version the caller read (`If-Match`, `_version`); null writes whatever the record holds now */ public function handle(Product $product, array $data, array $photos = [], ?UploadedFile $size_chart = null, ?array $expected = null): Product { return DB::transaction(function () use ($product, $data, $photos, $size_chart, $expected): Product { // Locked until the transaction ends: the version is compared, and the // write made, against one state, so two writers holding the same // version cannot both pass. $current = Product::query()->with(['tags'])->whereKey($product->getKey())->lockForUpdate()->firstOrFail(); if ($expected !== null && ! RecordVersion::matches($current, $expected, ['tags'])) { throw new StaleRecord; } $product->setRawAttributes($current->getRawOriginal(), sync: true); // A list the request leaves out stays as it is; an empty one clears it. $tagsIds = null; if (array_key_exists('tag_ids', $data) || array_key_exists('tag_new', $data)) { $tagsIds = CreatableTags::resolve( Tag::class, 'name', (array) ($data['tag_ids'] ?? []), (array) ($data['tag_new'] ?? []), 'tag_new', ); } unset($data['tag_ids'], $data['tag_new']); // Left out, every stored file stays; sent, it lists the ones to keep. $keptPhotos = array_key_exists('photos_existing', $data) ? array_values(array_intersect((array) $data['photos_existing'], $product->photos ?? [])) : ($product->photos ?? []); $storedPhotos = []; foreach ($photos as $file) { $storedPhotos[] = StoredFiles::store($file, 'products'); } $droppedPhotos = array_diff($product->photos ?? [], $keptPhotos); unset($data['photos_existing'], $data['photos_new']); $data['photos'] = array_merge($keptPhotos, $storedPhotos); DB::afterCommit(static function () use ($droppedPhotos): void { foreach ($droppedPhotos as $path) { StoredFiles::delete($path); } }); unset($data['size_chart']); if ($size_chart instanceof UploadedFile) { $replacedSizeChart = $product->size_chart; $data['size_chart'] = StoredFiles::store($size_chart, 'products'); if ($replacedSizeChart !== null && $replacedSizeChart !== '') { DB::afterCommit(static fn () => StoredFiles::delete($replacedSizeChart)); } } $enteringPublishedAt = ($data['status'] ?? $product->getRawOriginal('status')) === 'active'; $wasPublishedAt = $product->getRawOriginal('status') === 'active'; if ($enteringPublishedAt && ! $wasPublishedAt) { $data['published_at'] = now(); $data['published_by'] = auth()->id(); } elseif (! $enteringPublishedAt && $wasPublishedAt) { $data['published_at'] = null; $data['published_by'] = null; } $original = (array) $product->getOriginal(); $product->update($data); $changes = Arr::except($product->getChanges(), ['updated_at']); $before = Arr::only($original, array_keys($changes)); // A list reads as a list in the trail, not as the JSON the column holds. foreach (['photos'] as $list) { if (array_key_exists($list, $changes)) { $changes[$list] = json_decode((string) $changes[$list], true); } } if ($tagsIds !== null) { $synced = $product->tags()->sync($tagsIds); if ($synced['attached'] !== [] || $synced['detached'] !== []) { $changes['tags'] = ['attached' => $synced['attached'], 'detached' => array_values($synced['detached'])]; } } if ($changes !== []) { activity() ->performedOn($product) ->event('updated') ->withChanges(['old' => $before, 'attributes' => $changes]) ->log("Updated product \"{$product->name}\""); } return $product; }); } }