Managed error while generating URL previews by throwing an exception

This commit is contained in:
Alejandro Celaya
2016-08-18 11:16:56 +02:00
parent 277406c3b8
commit 60c68c914b
6 changed files with 48 additions and 4 deletions

View File

@@ -4,6 +4,7 @@ namespace Shlinkio\Shlink\Common\Service;
use Acelaya\ZsmAnnotatedServices\Annotation\Inject;
use Doctrine\Common\Cache\Cache;
use mikehaertl\wkhtmlto\Image;
use Shlinkio\Shlink\Common\Exception\PreviewGenerationException;
class PreviewGenerator implements PreviewGeneratorInterface
{
@@ -26,7 +27,7 @@ class PreviewGenerator implements PreviewGeneratorInterface
* @param Cache $cache
* @param string $location
*
* @Inject({Image::class, Cache::class, "config.phpwkhtmltopdf.images.files_location"})
* @Inject({Image::class, Cache::class, "config.phpwkhtmltopdf.files_location"})
*/
public function __construct(Image $image, Cache $cache, $location)
{
@@ -40,10 +41,11 @@ class PreviewGenerator implements PreviewGeneratorInterface
*
* @param string $url
* @return string
* @throws PreviewGenerationException
*/
public function generatePreview($url)
{
$cacheId = sprintf('preview_%s.png', urlencode($url));
$cacheId = sprintf('preview_%s.%s', urlencode($url), $this->image->type);
if ($this->cache->contains($cacheId)) {
return $this->cache->fetch($cacheId);
}
@@ -51,8 +53,15 @@ class PreviewGenerator implements PreviewGeneratorInterface
$path = $this->location . '/' . $cacheId;
$this->image->setPage($url);
$this->image->saveAs($path);
$this->cache->save($cacheId, $path);
// Check if an error occurred
$error = $this->image->getError();
if (! empty($error)) {
throw PreviewGenerationException::fromImageError($error);
}
// Cache the path and return it
$this->cache->save($cacheId, $path);
return $path;
}
}