src/Service/ResponsiveAssetsService.php line 19

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 $pathstring $packageNamestring $presetNamestring $extension 'jpg')
  14.     {
  15.         $extension strtolower($extension);
  16.         if (!in_array($extensionself::$allowedResponsiveImageExtensions)) {
  17.             throw new \RuntimeException(sprintf('Unexpected responsive image extension "%s". Allowed extensions: %s.'$extensionimplode(', '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 $pathstring $packageName)
  27.     {
  28.         $responsivePackageName $this->responsivePackageName($packageName);
  29.         if ($this->supportsResponsive($path$responsivePackageName)) {
  30.             $extension strtolower(pathinfo($pathPATHINFO_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 $pathstring $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($packageNameself::RESPONSIVE_PACKAGE_PREFIX)) {
  47.             return $packageName;
  48.         }
  49.         return self::RESPONSIVE_PACKAGE_PREFIX.$packageName;
  50.     }
  51. }