Skip to content

Commit

Permalink
TASK: Add safeguards against empty files or files that are larger tha…
Browse files Browse the repository at this point in the history
…n the original

in both cases the replacing is skipped.
  • Loading branch information
mficzel committed Oct 26, 2021
1 parent 4d7fbfc commit ec7b972
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions Classes/Service/ThumbnailOptimizationService.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ class ThumbnailOptimizationService
protected $resourceManager;

/**
* Optimize the given thumbnails using local copies that later replace the original resource
*
* @param Thumbnail $asset
*/
public function optimizeThumbnail(Thumbnail $thumbnail)
Expand Down Expand Up @@ -94,6 +96,29 @@ public function optimizeThumbnail(Thumbnail $thumbnail)
return;
}

$filesizeOriginal = filesize($tmpFileInput);
$filesizeOptimized = filesize($tmpFileOptimized);

if ($filesizeOriginal === false || $filesizeOptimized === false) {
$this->logger->error(sprintf('Optimizing image "%s" with command "%s" resulted in empty files', $thumbnail->getOriginalAsset()->getLabel(), $shellCommand), $output);
unlink($tmpFileInput);
unlink($tmpFileOptimized);
return;
}

if ($filesizeOptimized >= $filesizeOriginal) {
$this->logger->warning(sprintf(
'Optimizing image "%s" with command "%s" yielded no size reduction %s > %s bytes',
$thumbnail->getOriginalAsset()->getLabel(),
$shellCommand,
$filesizeOriginal,
$filesizeOptimized
));
unlink($tmpFileInput);
unlink($tmpFileOptimized);
return;
}

$this->logger->info(sprintf('Optimized image "%s" with command "%s"', $thumbnail->getOriginalAsset()->getLabel(), $shellCommand));
$optimizedResource = $this->resourceManager->importResource($tmpFileOptimized, $resource->getCollectionName());
$optimizedResource->setFilename($resource->getFilename());
Expand All @@ -105,6 +130,8 @@ public function optimizeThumbnail(Thumbnail $thumbnail)
}

/**
* Create a temporary path with the given postfix and return the result
*
* @param string $postfix
* @return string
*/
Expand All @@ -116,6 +143,11 @@ protected function createTemporaryPath(string $postfix): string
}

/**
* Create a temporary name for the image that will be optimized. The name has to be unique to avoid collisions
* in case of two processes try to optimize the same file
*
* @see: Neos\Flow\Classes\ResourceManagement\PersistentResource->createTemporaryLocalCopy
*
* @param PersistentResource $resource
* @return string
*/
Expand Down

0 comments on commit ec7b972

Please sign in to comment.