// Generate unique temporary file name
$tempFileName =
uniqid('CdnOptimizerTemp-', true
);
$mediaServiceAdapter =
$this->mediaService->
getFilesystem();
try { // Load file from remote filesystem, optimize it and upload it back again.
$this->filesystem->
writeStream($tempFileName,
$mediaServiceAdapter->
readStream($filepath));
$this->optimizerService->
optimize(sys_get_temp_dir() . '/' .
$tempFileName);
$mediaServiceAdapter->
updateStream($filepath,
$this->filesystem->
readStream($tempFileName));
} catch (\League\Flysystem\Exception
$exception) { throw $exception;
} finally { try { $this->filesystem->
delete($tempFileName);
} catch (Exception
$exception) { // Empty catch intended, an exception thrown here could hide possible other exception.
} } }