LazyLoadingFragmentHandler.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\DependencyInjection;
  11. use Psr\Container\ContainerInterface;
  12. use Symfony\Component\HttpFoundation\RequestStack;
  13. use Symfony\Component\HttpKernel\Controller\ControllerReference;
  14. use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
  15. /**
  16. * Lazily loads fragment renderers from the dependency injection container.
  17. *
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. */
  20. class LazyLoadingFragmentHandler extends FragmentHandler
  21. {
  22. private ContainerInterface $container;
  23. /**
  24. * @var array<string, bool>
  25. */
  26. private array $initialized = [];
  27. public function __construct(ContainerInterface $container, RequestStack $requestStack, bool $debug = false)
  28. {
  29. $this->container = $container;
  30. parent::__construct($requestStack, [], $debug);
  31. }
  32. public function render(string|ControllerReference $uri, string $renderer = 'inline', array $options = []): ?string
  33. {
  34. if (!isset($this->initialized[$renderer]) && $this->container->has($renderer)) {
  35. $this->addRenderer($this->container->get($renderer));
  36. $this->initialized[$renderer] = true;
  37. }
  38. return parent::render($uri, $renderer, $options);
  39. }
  40. }