5
5
namespace SpomkyLabs \PwaBundle \Normalizer ;
6
6
7
7
use SpomkyLabs \PwaBundle \Dto \Url ;
8
+ use Symfony \Component \AssetMapper \AssetMapperInterface ;
8
9
use Symfony \Component \Routing \RouterInterface ;
9
10
use Symfony \Component \Serializer \Normalizer \NormalizerAwareInterface ;
10
11
use Symfony \Component \Serializer \Normalizer \NormalizerAwareTrait ;
11
12
use Symfony \Component \Serializer \Normalizer \NormalizerInterface ;
13
+ use Throwable ;
12
14
use function assert ;
13
15
use const FILTER_VALIDATE_URL ;
14
16
@@ -18,18 +20,32 @@ final class UrlNormalizer implements NormalizerInterface, NormalizerAwareInterfa
18
20
19
21
public function __construct (
20
22
private readonly RouterInterface $ router ,
23
+ private readonly AssetMapperInterface $ assetMapper ,
21
24
) {
22
25
}
23
26
24
27
public function normalize (mixed $ object , string $ format = null , array $ context = []): string
25
28
{
26
29
assert ($ object instanceof Url);
27
30
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 ;
30
40
}
31
41
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
+ }
33
49
}
34
50
35
51
public function supportsNormalization (mixed $ data , string $ format = null , array $ context = []): bool
0 commit comments