vendor/sonata-project/block-bundle/src/Templating/Helper/BlockHelper.php line 154

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * This file is part of the Sonata Project package.
  5.  *
  6.  * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  7.  *
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11. namespace Sonata\BlockBundle\Templating\Helper;
  12. use Doctrine\Common\Util\ClassUtils;
  13. use Sonata\BlockBundle\Block\BlockContextInterface;
  14. use Sonata\BlockBundle\Block\BlockContextManagerInterface;
  15. use Sonata\BlockBundle\Block\BlockRendererInterface;
  16. use Sonata\BlockBundle\Block\BlockServiceManagerInterface;
  17. use Sonata\BlockBundle\Cache\HttpCacheHandlerInterface;
  18. use Sonata\BlockBundle\Event\BlockEvent;
  19. use Sonata\BlockBundle\Model\BlockInterface;
  20. use Sonata\Cache\CacheAdapterInterface;
  21. use Sonata\Cache\CacheManagerInterface;
  22. use Symfony\Component\EventDispatcher\EventDispatcherInterface as EventDispatcherComponentInterface;
  23. use Symfony\Component\HttpFoundation\Response;
  24. use Symfony\Component\Stopwatch\Stopwatch;
  25. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  26. class BlockHelper
  27. {
  28.     /**
  29.      * @var BlockServiceManagerInterface
  30.      */
  31.     private $blockServiceManager;
  32.     /**
  33.      * @var CacheManagerInterface|null
  34.      */
  35.     private $cacheManager;
  36.     /**
  37.      * @var array
  38.      */
  39.     private $cacheBlocks;
  40.     /**
  41.      * @var BlockRendererInterface
  42.      */
  43.     private $blockRenderer;
  44.     /**
  45.      * @var BlockContextManagerInterface
  46.      */
  47.     private $blockContextManager;
  48.     /**
  49.      * @var HttpCacheHandlerInterface|null
  50.      */
  51.     private $cacheHandler;
  52.     /**
  53.      * @var EventDispatcherInterface
  54.      */
  55.     private $eventDispatcher;
  56.     /**
  57.      * This property is a state variable holdings all assets used by the block for the current PHP request
  58.      * It is used to correctly render the javascripts and stylesheets tags on the main layout.
  59.      *
  60.      * @var array
  61.      */
  62.     private $assets;
  63.     /**
  64.      * @var array
  65.      */
  66.     private $traces;
  67.     /**
  68.      * @var Stopwatch|null
  69.      */
  70.     private $stopwatch;
  71.     public function __construct(
  72.         BlockServiceManagerInterface $blockServiceManager,
  73.         array $cacheBlocks,
  74.         BlockRendererInterface $blockRenderer,
  75.         BlockContextManagerInterface $blockContextManager,
  76.         EventDispatcherInterface $eventDispatcher,
  77.         ?CacheManagerInterface $cacheManager null,
  78.         ?HttpCacheHandlerInterface $cacheHandler null,
  79.         ?Stopwatch $stopwatch null
  80.     ) {
  81.         $this->blockServiceManager $blockServiceManager;
  82.         $this->cacheBlocks $cacheBlocks;
  83.         $this->blockRenderer $blockRenderer;
  84.         $this->eventDispatcher $eventDispatcher;
  85.         $this->cacheManager $cacheManager;
  86.         $this->blockContextManager $blockContextManager;
  87.         $this->cacheHandler $cacheHandler;
  88.         $this->stopwatch $stopwatch;
  89.         $this->assets = [
  90.             'js' => [],
  91.             'css' => [],
  92.         ];
  93.         $this->traces = [
  94.             '_events' => [],
  95.         ];
  96.     }
  97.     /**
  98.      * @param string $media    Unused, only kept to not break existing code
  99.      * @param string $basePath Base path to prepend to the stylesheet urls
  100.      *
  101.      * @return array|string
  102.      */
  103.     public function includeJavascripts($media$basePath '')
  104.     {
  105.         $html '';
  106.         foreach ($this->assets['js'] as $javascript) {
  107.             $html .= "\n".sprintf('<script src="%s%s" type="text/javascript"></script>'$basePath$javascript);
  108.         }
  109.         return $html;
  110.     }
  111.     /**
  112.      * @param string $media    The css media type to use: all|screen|...
  113.      * @param string $basePath Base path to prepend to the stylesheet urls
  114.      *
  115.      * @return array|string
  116.      */
  117.     public function includeStylesheets($media$basePath '')
  118.     {
  119.         if (=== \count($this->assets['css'])) {
  120.             return '';
  121.         }
  122.         $html sprintf("<style type='text/css' media='%s'>"$media);
  123.         foreach ($this->assets['css'] as $stylesheet) {
  124.             $html .= "\n".sprintf('@import url(%s%s);'$basePath$stylesheet);
  125.         }
  126.         $html .= "\n</style>";
  127.         return $html;
  128.     }
  129.     public function renderEvent(string $name, array $options = []): string
  130.     {
  131.         $eventName sprintf('sonata.block.event.%s'$name);
  132.         $event $this->eventDispatcher->dispatch(new BlockEvent($options), $eventName);
  133.         \assert($event instanceof BlockEvent);
  134.         $content '';
  135.         foreach ($event->getBlocks() as $block) {
  136.             $content .= $this->render($block);
  137.         }
  138.         if (null !== $this->stopwatch) {
  139.             $this->traces['_events'][uniqid(''true)] = [
  140.                 'template_code' => $name,
  141.                 'event_name' => $eventName,
  142.                 'blocks' => $this->getEventBlocks($event),
  143.                 'listeners' => $this->getEventListeners($eventName),
  144.             ];
  145.         }
  146.         return $content;
  147.     }
  148.     /**
  149.      * Check if a given block type exists.
  150.      *
  151.      * @param string $type Block type to check for
  152.      */
  153.     public function exists(string $type): bool
  154.     {
  155.         return $this->blockContextManager->exists($type);
  156.     }
  157.     /**
  158.      * @param mixed $block
  159.      */
  160.     public function render($block, array $options = []): string
  161.     {
  162.         $blockContext $this->blockContextManager->get($block$options);
  163.         if (!$blockContext instanceof BlockContextInterface) {
  164.             return '';
  165.         }
  166.         $stats = [];
  167.         if ($this->stopwatch) {
  168.             $stats $this->startTracing($blockContext->getBlock());
  169.         }
  170.         $service $this->blockServiceManager->get($blockContext->getBlock());
  171.         $useCache $blockContext->getSetting('use_cache');
  172.         $cacheKeys $response false;
  173.         $cacheService $useCache $this->getCacheService($blockContext->getBlock(), $stats) : false;
  174.         if ($cacheService) {
  175.             $cacheKeys array_merge(
  176.                 $service->getCacheKeys($blockContext->getBlock()),
  177.                 $blockContext->getSetting('extra_cache_keys')
  178.             );
  179.             if ($this->stopwatch) {
  180.                 $stats['cache']['keys'] = $cacheKeys;
  181.             }
  182.             // Please note, some cache handler will always return true (js for instance)
  183.             // This will allows to have a non cacheable block, but the global page can still be cached by
  184.             // a reverse proxy, as the generated page will never get the generated Response from the block.
  185.             if ($cacheService->has($cacheKeys)) {
  186.                 $cacheElement $cacheService->get($cacheKeys);
  187.                 if ($this->stopwatch) {
  188.                     $stats['cache']['from_cache'] = false;
  189.                 }
  190.                 if (!$cacheElement->isExpired() && $cacheElement->getData() instanceof Response) {
  191.                     /* @var Response $response */
  192.                     if ($this->stopwatch) {
  193.                         $stats['cache']['from_cache'] = true;
  194.                     }
  195.                     $response $cacheElement->getData();
  196.                 }
  197.             }
  198.         }
  199.         if (!$response) {
  200.             $recorder null;
  201.             if ($this->cacheManager) {
  202.                 $recorder $this->cacheManager->getRecorder();
  203.                 $recorder->add($blockContext->getBlock());
  204.                 $recorder->push();
  205.             }
  206.             $response $this->blockRenderer->render($blockContext);
  207.             $contextualKeys $recorder $recorder->pop() : [];
  208.             if ($this->stopwatch) {
  209.                 $stats['cache']['contextual_keys'] = $contextualKeys;
  210.             }
  211.             if ($response->isCacheable() && $cacheKeys && $cacheService) {
  212.                 $cacheService->set($cacheKeys$response, (int) $response->getTtl(), $contextualKeys);
  213.             }
  214.         }
  215.         if ($this->stopwatch) {
  216.             // avoid \DateTime because of serialize/unserialize issue in PHP7.3 (https://bugs.php.net/bug.php?id=77302)
  217.             $stats['cache']['created_at'] = null === $response->getDate() ? null $response->getDate()->getTimestamp();
  218.             $stats['cache']['ttl'] = $response->getTtl() ?: 0;
  219.             $stats['cache']['age'] = $response->getAge();
  220.         }
  221.         // update final ttl for the whole Response
  222.         if ($this->cacheHandler) {
  223.             $this->cacheHandler->updateMetadata($response$blockContext);
  224.         }
  225.         if ($this->stopwatch) {
  226.             $this->stopTracing($blockContext->getBlock(), $stats);
  227.         }
  228.         return (string) $response->getContent();
  229.     }
  230.     /**
  231.      * Returns the rendering traces.
  232.      */
  233.     public function getTraces(): array
  234.     {
  235.         return $this->traces;
  236.     }
  237.     private function stopTracing(BlockInterface $block, array $stats): void
  238.     {
  239.         $e $this->traces[$block->getId()]->stop();
  240.         $this->traces[$block->getId()] = array_merge($stats, [
  241.             'duration' => $e->getDuration(),
  242.             'memory_end' => memory_get_usage(true),
  243.             'memory_peak' => memory_get_peak_usage(true),
  244.         ]);
  245.         $this->traces[$block->getId()]['cache']['lifetime'] = $this->traces[$block->getId()]['cache']['age'] + $this->traces[$block->getId()]['cache']['ttl'];
  246.     }
  247.     private function getEventBlocks(BlockEvent $event): array
  248.     {
  249.         $results = [];
  250.         foreach ($event->getBlocks() as $block) {
  251.             $results[] = [$block->getId(), $block->getType()];
  252.         }
  253.         return $results;
  254.     }
  255.     private function getEventListeners(string $eventName): array
  256.     {
  257.         $results = [];
  258.         if (!$this->eventDispatcher instanceof EventDispatcherComponentInterface) {
  259.             return $results;
  260.         }
  261.         foreach ($this->eventDispatcher->getListeners($eventName) as $listener) {
  262.             if ($listener instanceof \Closure) {
  263.                 $results[] = '{closure}()';
  264.             } elseif (\is_object($listener[0])) {
  265.                 $results[] = \get_class($listener[0]);
  266.             } elseif (\is_string($listener[0])) {
  267.                 $results[] = $listener[0];
  268.             } else {
  269.                 $results[] = 'Unknown type!';
  270.             }
  271.         }
  272.         return $results;
  273.     }
  274.     private function getCacheService(BlockInterface $block, array &$stats null): ?CacheAdapterInterface
  275.     {
  276.         if (!$this->cacheManager) {
  277.             return null;
  278.         }
  279.         // type by block class
  280.         $class ClassUtils::getClass($block);
  281.         $cacheServiceId $this->cacheBlocks['by_class'][$class] ?? null;
  282.         // type by block service
  283.         if (null === $cacheServiceId) {
  284.             $cacheServiceId $this->cacheBlocks['by_type'][$block->getType()] ?? null;
  285.         }
  286.         if (null === $cacheServiceId) {
  287.             return null;
  288.         }
  289.         if ($this->stopwatch) {
  290.             $stats['cache']['handler'] = $cacheServiceId;
  291.         }
  292.         return $this->cacheManager->getCacheService((string) $cacheServiceId);
  293.     }
  294.     private function startTracing(BlockInterface $block): array
  295.     {
  296.         if (null !== $this->stopwatch) {
  297.             $this->traces[$block->getId()] = $this->stopwatch->start(
  298.                 sprintf('%s (id: %s, type: %s)'$block->getName(), $block->getId(), $block->getType())
  299.             );
  300.         }
  301.         return [
  302.             'name' => $block->getName(),
  303.             'type' => $block->getType(),
  304.             'duration' => false,
  305.             'memory_start' => memory_get_usage(true),
  306.             'memory_end' => false,
  307.             'memory_peak' => false,
  308.             'cache' => [
  309.                 'keys' => [],
  310.                 'contextual_keys' => [],
  311.                 'handler' => false,
  312.                 'from_cache' => false,
  313.                 'ttl' => 0,
  314.                 'created_at' => false,
  315.                 'lifetime' => 0,
  316.                 'age' => 0,
  317.             ],
  318.             'assets' => [
  319.                 'js' => [],
  320.                 'css' => [],
  321.             ],
  322.         ];
  323.     }
  324. }