Skip to content

Commit e158525

Browse files
committed
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.
1 parent a6f0a81 commit e158525

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

src/Normalizer/UrlNormalizer.php

+19-3
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,12 @@
55
namespace SpomkyLabs\PwaBundle\Normalizer;
66

77
use SpomkyLabs\PwaBundle\Dto\Url;
8+
use Symfony\Component\AssetMapper\AssetMapperInterface;
89
use Symfony\Component\Routing\RouterInterface;
910
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
1011
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
1112
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
13+
use Throwable;
1214
use function assert;
1315
use const FILTER_VALIDATE_URL;
1416

@@ -18,18 +20,32 @@ final class UrlNormalizer implements NormalizerInterface, NormalizerAwareInterfa
1820

1921
public function __construct(
2022
private readonly RouterInterface $router,
23+
private readonly AssetMapperInterface $assetMapper,
2124
) {
2225
}
2326

2427
public function normalize(mixed $object, string $format = null, array $context = []): string
2528
{
2629
assert($object instanceof Url);
2730

28-
if (! str_starts_with($object->path, '/') && filter_var($object->path, FILTER_VALIDATE_URL) === false) {
29-
return $this->router->generate($object->path, $object->params, $object->pathTypeReference);
31+
// If the path is a valid URL, we return it directly
32+
if (str_starts_with($object->path, '/') && filter_var($object->path, FILTER_VALIDATE_URL) !== false) {
33+
return $object->path;
34+
}
35+
36+
// If the path is an asset, we return the public path
37+
$asset = $this->assetMapper->getAsset($object->path);
38+
if ($asset !== null) {
39+
return $asset->publicPath;
3040
}
3141

32-
return $object->path;
42+
// Otherwise, we try to generate the URL
43+
try {
44+
return $this->router->generate($object->path, $object->params, $object->pathTypeReference);
45+
} catch (Throwable) {
46+
// If the URL cannot be generated, we return the path as is
47+
return $object->path;
48+
}
3349
}
3450

3551
public function supportsNormalization(mixed $data, string $format = null, array $context = []): bool

0 commit comments

Comments
 (0)