$quality */ public function optimize( UploadedFile $file, int $quality = self::DEFAULT_QUALITY, ): \SplFileObject { try { if (! $this->isImage($file)) { return $this->toFileObject($file); } $bytes = Image::fromUpload($file) ->quality(clamp($quality, 1, 100)) ->toBytes(); if ($bytes === false) { throw new ImageOptimizerException('Could not read image bytes.'); } return $this->temporaryFileFactory->newWithBytes( $bytes, $file->getClientOriginalName() ); } catch (\Throwable $e) { $this->logger->warning( "Image optimization skipped for [{$file->getClientOriginalName()}]: {$e->getMessage()}", ['exception' => $e], ); return $this->toFileObject($file); } } private function toFileObject(UploadedFile $file): \SplFileObject { $bytes = $file->get(); if ($bytes === false) { throw new ImageOptimizerException('Could not read the uploaded file bytes.'); } return $this->temporaryFileFactory->newWithBytes($bytes, $file->getClientOriginalName()); } 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); } }