|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <[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 | +namespace Symfony\UX\Turbo\Twig; |
| 13 | + |
| 14 | +use Psr\Container\ContainerInterface; |
| 15 | +use Symfony\Component\HttpFoundation\RequestStack; |
| 16 | +use Symfony\Component\Mercure\Authorization; |
| 17 | +use Symfony\UX\Turbo\Bridge\Mercure\TopicSet; |
| 18 | +use Twig\Environment; |
| 19 | +use Twig\Extension\RuntimeExtensionInterface; |
| 20 | + |
| 21 | +/** |
| 22 | + * @author Pierre Ambroise <[email protected]> |
| 23 | + * |
| 24 | + * @internal |
| 25 | + */ |
| 26 | +class TurboRuntime implements RuntimeExtensionInterface |
| 27 | +{ |
| 28 | + public function __construct( |
| 29 | + private ContainerInterface $turboStreamListenRenderers, |
| 30 | + private string $default, |
| 31 | + private ?Authorization $authorization = null, |
| 32 | + private ?RequestStack $requestStack = null, |
| 33 | + ) { |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * @param object|string|array<object|string> $topic |
| 38 | + * @param array<string, mixed> $options |
| 39 | + */ |
| 40 | + public function renderTurboStreamListen(Environment $env, $topic, ?string $transport = null, array $options = []): string |
| 41 | + { |
| 42 | + $transport ??= $this->default; |
| 43 | + |
| 44 | + if (!$this->turboStreamListenRenderers->has($transport)) { |
| 45 | + throw new \InvalidArgumentException(\sprintf('The Turbo stream transport "%s" does not exist.', $transport)); |
| 46 | + } |
| 47 | + |
| 48 | + if (\is_array($topic)) { |
| 49 | + $topic = new TopicSet($topic); |
| 50 | + } |
| 51 | + |
| 52 | + if ( |
| 53 | + null !== $this->authorization |
| 54 | + && null !== $this->requestStack |
| 55 | + && (isset($options['subscribe']) || isset($options['publish']) || isset($options['additionalClaims'])) |
| 56 | + && null !== $request = $this->requestStack->getMainRequest() |
| 57 | + ) { |
| 58 | + $this->authorization->setCookie( |
| 59 | + $request, |
| 60 | + $options['subscribe'] ?? [], |
| 61 | + $options['publish'] ?? [], |
| 62 | + $options['additionalClaims'] ?? [], |
| 63 | + $transport, |
| 64 | + ); |
| 65 | + |
| 66 | + unset($options['subscribe'], $options['publish'], $options['additionalClaims']); |
| 67 | + } |
| 68 | + |
| 69 | + return $this->turboStreamListenRenderers->get($transport)->renderTurboStreamListen($env, $topic, $options); |
| 70 | + } |
| 71 | +} |
0 commit comments