src/Service/ResponsiveAssetsService.php line 49

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Bridge\Symfony\Asset\VersionStrategy\ResponsiveAssetStrategy;
  4. use Symfony\Component\Asset\Exception\InvalidArgumentException;
  5. use Symfony\Component\Asset\Packages;
  6. class ResponsiveAssetsService
  7. {
  8.     const RESPONSIVE_PACKAGE_PREFIX = 'responsive_';
  9.     private static array $allowedResponsiveImageExtensions = ['jpg', 'webp'];
  10.     public function __construct(
  11.         private Packages $packages
  12.     ) {}
  13.     public function getResponsiveImageUrl(string $path, string $packageName, string $presetName, string $extension = 'jpg')
  14.     {
  15.         $extension = strtolower($extension);
  16.         if (!in_array($extension, self::$allowedResponsiveImageExtensions)) {
  17.             throw new \RuntimeException(sprintf('Unexpected responsive image extension "%s". Allowed extensions: %s.', $extension, implode(', ', self::$allowedResponsiveImageExtensions)));
  18.         }
  19.         $responsivePackageName = $this->responsivePackageName($packageName);
  20.         if ($this->supportsResponsive($path, $responsivePackageName)) {
  21.             $path = sprintf('%s/%s.%s', $path, $presetName, $extension);
  22.             return $this->packages->getUrl($path, $responsivePackageName);
  23.         }
  24.         return $this->packages->getUrl($path, $packageName);
  25.     }
  26.     public function getStreamUrl(string $path, string $packageName)
  27.     {
  28.         $responsivePackageName = $this->responsivePackageName($packageName);
  29.         if ($this->supportsResponsive($path, $responsivePackageName)) {
  30.             $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
  31.             $path = sprintf('%s/stream.%s', $path, $extension);
  32.             return $this->packages->getUrl($path, $responsivePackageName);
  33.         }
  34.         return $this->packages->getUrl($path, $packageName);
  35.     }
  36.     private function supportsResponsive(string $path, string $packageName): bool
  37.     {
  38.         try {
  39.             return ResponsiveAssetStrategy::NAME === $this->packages->getVersion($path, $packageName);
  40.         } catch (InvalidArgumentException $ex) { // Исключение будет, если пакета с указанным именем не существует
  41.             return false;
  42.         }
  43.     }
  44.     private function responsivePackageName(string $packageName): string
  45.     {
  46.         if (false !== strpos($packageName, self::RESPONSIVE_PACKAGE_PREFIX)) {
  47.             return $packageName;
  48.         }
  49.         return self::RESPONSIVE_PACKAGE_PREFIX.$packageName;
  50.     }
  51. }