From e1585257c1c7caf421e5be16934564f37c43d577 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 22 Apr 2024 20:16:56 +0200 Subject: [PATCH] Add AssetMapper to UrlNormalizer Integrated the AssetMapperInterface into the UrlNormalizer class. Updated the process to check if the path is an asset and return the public path accordingly. Also, added error handling in the case of URL generation failure. --- src/Normalizer/UrlNormalizer.php | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/Normalizer/UrlNormalizer.php b/src/Normalizer/UrlNormalizer.php index ea35626..e373fef 100644 --- a/src/Normalizer/UrlNormalizer.php +++ b/src/Normalizer/UrlNormalizer.php @@ -5,10 +5,12 @@ namespace SpomkyLabs\PwaBundle\Normalizer; use SpomkyLabs\PwaBundle\Dto\Url; +use Symfony\Component\AssetMapper\AssetMapperInterface; use Symfony\Component\Routing\RouterInterface; use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; +use Throwable; use function assert; use const FILTER_VALIDATE_URL; @@ -18,6 +20,7 @@ final class UrlNormalizer implements NormalizerInterface, NormalizerAwareInterfa public function __construct( private readonly RouterInterface $router, + private readonly AssetMapperInterface $assetMapper, ) { } @@ -25,11 +28,24 @@ public function normalize(mixed $object, string $format = null, array $context = { assert($object instanceof Url); - if (! str_starts_with($object->path, '/') && filter_var($object->path, FILTER_VALIDATE_URL) === false) { - return $this->router->generate($object->path, $object->params, $object->pathTypeReference); + // If the path is a valid URL, we return it directly + if (str_starts_with($object->path, '/') && filter_var($object->path, FILTER_VALIDATE_URL) !== false) { + return $object->path; + } + + // If the path is an asset, we return the public path + $asset = $this->assetMapper->getAsset($object->path); + if ($asset !== null) { + return $asset->publicPath; } - return $object->path; + // Otherwise, we try to generate the URL + try { + return $this->router->generate($object->path, $object->params, $object->pathTypeReference); + } catch (Throwable) { + // If the URL cannot be generated, we return the path as is + return $object->path; + } } public function supportsNormalization(mixed $data, string $format = null, array $context = []): bool