|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the API Platform project. |
| 5 | + * |
| 6 | + * (c) Kévin Dunglas <[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 ApiPlatform\Hydra\State; |
| 15 | + |
| 16 | +use ApiPlatform\Api\UrlGeneratorInterface; |
| 17 | +use ApiPlatform\JsonLd\ContextBuilder; |
| 18 | +use ApiPlatform\Metadata\Operation; |
| 19 | +use ApiPlatform\State\ProcessorInterface; |
| 20 | +use Symfony\Component\WebLink\GenericLinkProvider; |
| 21 | +use Symfony\Component\WebLink\Link; |
| 22 | + |
| 23 | +final class HydraLinkProcessor implements ProcessorInterface |
| 24 | +{ |
| 25 | + /** |
| 26 | + * @param ProcessorInterface<mixed> $inner |
| 27 | + */ |
| 28 | + public function __construct(private readonly ProcessorInterface $inner, private readonly UrlGeneratorInterface $urlGenerator) |
| 29 | + { |
| 30 | + } |
| 31 | + |
| 32 | + public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed |
| 33 | + { |
| 34 | + if (!($request = $context['request'] ?? null)) { |
| 35 | + return $this->inner->process($data, $operation, $uriVariables, $context); |
| 36 | + } |
| 37 | + |
| 38 | + $apiDocUrl = $this->urlGenerator->generate('api_doc', ['_format' => 'jsonld'], UrlGeneratorInterface::ABS_URL); |
| 39 | + $link = new Link(ContextBuilder::HYDRA_NS.'apiDocumentation', $apiDocUrl); |
| 40 | + $linkProvider = $request->attributes->get('_links') ?? new GenericLinkProvider(); |
| 41 | + $request->attributes->set('_links', $linkProvider->withLink($link)); |
| 42 | + |
| 43 | + return $this->inner->process($data, $operation, $uriVariables, $context); |
| 44 | + } |
| 45 | +} |
0 commit comments