1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Silverback API Components Bundle Project |
5
|
|
|
* |
6
|
|
|
* (c) Daniel West <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Silverback\ApiComponentsBundle\Serializer\Normalizer; |
15
|
|
|
|
16
|
|
|
use Silverback\ApiComponentsBundle\Entity\Core\Route; |
17
|
|
|
use Symfony\Component\Serializer\Exception\CircularReferenceException; |
18
|
|
|
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface; |
19
|
|
|
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface; |
20
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; |
21
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @author Daniel West <[email protected]> |
25
|
|
|
*/ |
26
|
|
|
class RouteNormalizer implements ContextAwareNormalizerInterface, CacheableSupportsMethodInterface, NormalizerAwareInterface |
27
|
|
|
{ |
28
|
|
|
use NormalizerAwareTrait; |
29
|
|
|
|
30
|
|
|
private const ALREADY_CALLED = 'ROUTE_NORMALIZER_ALREADY_CALLED'; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param Route $object |
34
|
|
|
* @param mixed|null $format |
35
|
|
|
*/ |
36
|
|
|
public function normalize($object, $format = null, array $context = []) |
37
|
|
|
{ |
38
|
|
|
$context[self::ALREADY_CALLED] = true; |
39
|
|
|
|
40
|
|
|
$finalRoute = $object; |
41
|
|
|
$redirectedRoutes = [$finalRoute->getId()]; |
42
|
|
|
while (($nextRedirect = $finalRoute->getRedirect())) { |
43
|
|
|
if (\in_array($nextRedirect->getId(), $redirectedRoutes, true)) { |
44
|
|
|
throw new CircularReferenceException(sprintf('The redirect routes result in a circular reference: %s', implode(' -> ', $redirectedRoutes))); |
45
|
|
|
} |
46
|
|
|
$redirectedRoutes[] = $nextRedirect->getId(); |
47
|
|
|
$finalRoute = $nextRedirect; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$isRedirect = $finalRoute !== $object; |
51
|
|
|
if ($isRedirect) { |
52
|
|
|
$object->setPage($finalRoute->getPage()); |
53
|
|
|
$object->setPageData($finalRoute->getPageData()); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$normalized = $this->normalizer->normalize($object, $format, $context); |
57
|
|
|
|
58
|
|
|
if ($isRedirect) { |
59
|
|
|
$normalized['redirectPath'] = $finalRoute->getPath(); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return $normalized; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function supportsNormalization($data, $format = null, $context = []): bool |
66
|
|
|
{ |
67
|
|
|
return !isset($context[self::ALREADY_CALLED]) && $data instanceof Route; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
public function hasCacheableSupportsMethod(): bool |
71
|
|
|
{ |
72
|
|
|
return false; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|