src/Service/UrlImageCacheService.php line 55

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Controller\ImageCache\ImageManager;
  4. use Symfony\Component\DependencyInjection\ContainerInterface;
  5. class UrlImageCacheService
  6. {
  7. protected $cacheDir;
  8. protected $container;
  9. private $imageManager;
  10. public function __construct(ContainerInterface $container)
  11. {
  12. $this->container = $container;
  13. $this->cacheDir = $this->container->getParameter('kernel.project_dir') . '/public/cache/images';
  14. $this->imageManager = new ImageManager($this->container);
  15. }
  16. public function getCachedImage(string $url, string $domain): string
  17. {
  18. $cacheKey = md5($url);
  19. $cachePath = $this->cacheDir . '/' . $cacheKey . '.png';
  20. // Ensure the cache directory exists
  21. if (! is_dir($this->cacheDir)) {
  22. mkdir($this->cacheDir, 0775, true);
  23. }
  24. if ($this->isCacheExpired($cachePath)) {
  25. if (file_exists($cachePath)) {
  26. unlink($cachePath); // Delete the file
  27. }
  28. $this->cacheImage($url, $cachePath, $domain);
  29. }
  30. return $cachePath;
  31. }
  32. private function isCacheExpired(string $cachePath): bool
  33. {
  34. if (!file_exists($cachePath)) {
  35. return true;
  36. }
  37. $cacheLifetime = 7 * 24 * 60 * 60; // 1 week in seconds
  38. return (time() - filemtime($cachePath)) > $cacheLifetime;
  39. }
  40. private function cacheImage(string $url, string $cachePath, string $domain): void
  41. {
  42. $image = $this->imageManager->make([
  43. 'imageUrl' => $url,
  44. 'siteUrl' => $domain
  45. ]);
  46. $image->save($cachePath);
  47. }
  48. }