$quality * * @throws ImageOptimizerException If the image could not be optimized. */ public function optimize( UploadedFile $file, int $quality = self::DEFAULT_QUALITY, ): UploadedFile { if (! $this->isImage($file)) { return $file; } try { $image = Image::fromUpload($file) ->quality(clamp($quality, 1, 100)); $tempPath = tempnam(sys_get_temp_dir(), 'opt_'); if ($tempPath === false || file_put_contents($tempPath, $image->toBytes()) === false) { throw new ImageOptimizerException('Could not persist optimized image to temporary disk.'); } return new AutoCleanupUploadedFile( path: $tempPath, originalName: $file->getClientOriginalName(), mimeType: $file->getMimeType() ?? 'image/jpeg', error: UPLOAD_ERR_OK, test: true, ); } catch (\Throwable $e) { $this->logger?->warning( "Image optimization skipped for [{$file->getClientOriginalName()}]: {$e->getMessage()}", ['exception' => $e], ); return $file; } } private function isImage(UploadedFile $file): bool { if (! $file->isValid() || ! $file->isReadable()) { return false; } $mime = strtolower((string) $file->getMimeType()); return in_array($mime, self::SUPPORTED_MIMES, true); } }