<?php
namespace App\Service;
use App\Bridge\Symfony\Asset\VersionStrategy\ResponsiveAssetStrategy;
use Symfony\Component\Asset\Exception\InvalidArgumentException;
use Symfony\Component\Asset\Packages;
class ResponsiveAssetsService
{
const RESPONSIVE_PACKAGE_PREFIX = 'responsive_';
private static array $allowedResponsiveImageExtensions = ['jpg', 'webp'];
public function __construct(
private Packages $packages
) {}
public function getResponsiveImageUrl(string $path, string $packageName, string $presetName, string $extension = 'jpg')
{
$extension = strtolower($extension);
if (!in_array($extension, self::$allowedResponsiveImageExtensions)) {
throw new \RuntimeException(sprintf('Unexpected responsive image extension "%s". Allowed extensions: %s.', $extension, implode(', ', self::$allowedResponsiveImageExtensions)));
}
$responsivePackageName = $this->responsivePackageName($packageName);
if ($this->supportsResponsive($path, $responsivePackageName)) {
$path = sprintf('%s/%s.%s', $path, $presetName, $extension);
return $this->packages->getUrl($path, $responsivePackageName);
}
return $this->packages->getUrl($path, $packageName);
}
public function getStreamUrl(string $path, string $packageName)
{
$responsivePackageName = $this->responsivePackageName($packageName);
if ($this->supportsResponsive($path, $responsivePackageName)) {
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$path = sprintf('%s/stream.%s', $path, $extension);
return $this->packages->getUrl($path, $responsivePackageName);
}
return $this->packages->getUrl($path, $packageName);
}
private function supportsResponsive(string $path, string $packageName): bool
{
try {
return ResponsiveAssetStrategy::NAME === $this->packages->getVersion($path, $packageName);
} catch (InvalidArgumentException $ex) { // Исключение будет, если пакета с указанным именем не существует
return false;
}
}
private function responsivePackageName(string $packageName): string
{
if (false !== strpos($packageName, self::RESPONSIVE_PACKAGE_PREFIX)) {
return $packageName;
}
return self::RESPONSIVE_PACKAGE_PREFIX.$packageName;
}
}