Debian Codegraph @

lib/3rdParty/composer/web-auth/webauthn-lib/src/Denormalizer/UrlNormalizer.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Webauthn\Denormalizer;
6
7 use function assert;
8 use const FILTER_VALIDATE_URL;
9 use function filter_var;
10 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
11 use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
12 use Throwable;
13 use Webauthn\Url;
14
15 /**
16 * Normalizes Url objects to absolute HTTPS URLs.
17 * Either returns the URL directly if already absolute, or generates it from a Symfony route.
18 */
19 final readonly class UrlNormalizer implements NormalizerInterface
20 {
21 public function __construct(
22 private ?UrlGeneratorInterface $urlGenerator = null,
23 ) {
24 }
25
26 public function normalize(mixed $data, ?string $format = null, array $context = []): string
27 {
28 assert($data instanceof Url);
29
30 // If no URL generator available, return the path as-is
31 if ($this->urlGenerator === null) {
32 return $data->path;
33 }
34
35 // If the path is already a valid absolute URL (https://...), return it directly
36 if (filter_var($data->path, FILTER_VALIDATE_URL) !== false) {
37 return $data->path;
38 }
39
40 // Otherwise, try to generate an absolute URL from a Symfony route name
41 try {
42 return $this->urlGenerator->generate($data->path, $data->params, UrlGeneratorInterface::ABSOLUTE_URL);
43 } catch (Throwable) {
44 // If the URL cannot be generated, return the path as is
45 return $data->path;
46 }
47 }
48
49 public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
50 {
51 return $data instanceof Url;
52 }
53
54 /**
55 * @return array<class-string, bool>
56 */
57 public function getSupportedTypes(?string $format): array
58 {
59 return [
60 Url::class => true,
61 ];
62 }
63 }