forgetCaches(); $this->imageVariants($product, created: true); } /** * Handle the Product "updated" event. */ public function updated(Product $product): void { $this->forgetCaches(); $this->imageVariants($product, created: false); } /** * Handle the Product "deleted" event. */ public function deleted(Product $product): void { $this->forgetCaches(); } /** * Handle the Product "restored" event. */ public function restored(Product $product): void { $this->forgetCaches(); } /** * Handle the Product "forceDeleted" event. */ public function forceDeleted(Product $product): void { $this->forgetCaches(); $this->discardFiles($product); $this->discardImageVariants($product); } /** * After the commit, so a rollback cannot leave a row pointing at a file * already gone. Failures are logged, not raised: the record is deleted either way. */ private function discardFiles(Product $product): void { $paths = array_filter([ ...array_values($product->photos ?? []), $product->size_chart, ], static fn (mixed $path): bool => is_string($path) && $path !== ''); if ($paths === []) { return; } DB::afterCommit(static function () use ($paths): void { foreach ($paths as $path) { try { StoredFiles::delete($path); } catch (Throwable $e) { Log::warning('Orphaned product upload left on disk after force delete.', [ 'path' => $path, 'reason' => $e->getMessage(), ]); } } }); } /** * The sizes of each image this write stored, built once it has committed * (`image;variants`); the sizes of each image it replaced, removed. */ private function imageVariants(Product $product, bool $created): void { foreach (Product::IMAGE_VARIANTS as $column => $sizes) { if (! $created && ! $product->wasChanged($column)) { continue; } $now = array_filter((array) ($product->getAttribute($column) ?? []), 'is_string'); $before = $created ? [] : array_filter((array) ($product->getOriginal($column) ?? []), 'is_string'); foreach (array_diff($now, $before) as $path) { MakeImageVariants::dispatch($path, $sizes)->afterCommit(); } $gone = array_values(array_diff($before, $now)); if ($gone !== []) { DB::afterCommit(static function () use ($gone, $sizes): void { foreach ($gone as $path) { ImageVariants::delete($path, $sizes); } }); } } } /** The sizes of every image the row held — after the commit, like the originals. */ private function discardImageVariants(Product $product): void { foreach (Product::IMAGE_VARIANTS as $column => $sizes) { $paths = array_values(array_filter((array) ($product->getAttribute($column) ?? []), 'is_string')); DB::afterCommit(static function () use ($paths, $sizes): void { foreach ($paths as $path) { ImageVariants::delete($path, $sizes); } }); } } /** Every cache derived from this table, invalidated together. */ private function forgetCaches(): void { ProductStats::forget(); } }