Skip to content

Commit

Permalink
Add AssetMapper to UrlNormalizer
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Spomky committed Apr 22, 2024
1 parent a6f0a81 commit e158525
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions src/Normalizer/UrlNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

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

public function __construct(
private readonly RouterInterface $router,
private readonly AssetMapperInterface $assetMapper,
) {
}

public function normalize(mixed $object, string $format = null, array $context = []): string
{
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
Expand Down

0 comments on commit e158525

Please sign in to comment.