vendor/sulu/sulu/src/Sulu/Bundle/SnippetBundle/Twig/SnippetAreaTwigExtension.php line 52

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of Sulu.
  4. *
  5. * (c) Sulu GmbH
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace Sulu\Bundle\SnippetBundle\Twig;
  11. use Sulu\Bundle\SnippetBundle\Snippet\DefaultSnippetManagerInterface;
  12. use Sulu\Bundle\SnippetBundle\Snippet\SnippetResolverInterface;
  13. use Sulu\Bundle\SnippetBundle\Snippet\WrongSnippetTypeException;
  14. use Sulu\Bundle\WebsiteBundle\ReferenceStore\ReferenceStoreInterface;
  15. use Sulu\Component\DocumentManager\Exception\DocumentNotFoundException;
  16. use Sulu\Component\Webspace\Analyzer\RequestAnalyzerInterface;
  17. use Twig\Extension\AbstractExtension;
  18. use Twig\TwigFunction;
  19. /**
  20. * Provides snippets by area.
  21. */
  22. class SnippetAreaTwigExtension extends AbstractExtension
  23. {
  24. public function __construct(
  25. private DefaultSnippetManagerInterface $defaultSnippetManager,
  26. private RequestAnalyzerInterface $requestAnalyzer,
  27. private SnippetResolverInterface $snippetResolver,
  28. private ReferenceStoreInterface $snippetAreaReferenceStore,
  29. ) {
  30. }
  31. public function getFunctions()
  32. {
  33. return [
  34. new TwigFunction('sulu_snippet_load_by_area', [$this, 'loadByArea']),
  35. ];
  36. }
  37. /**
  38. * Load snippet for webspace by area.
  39. *
  40. * @param string $area
  41. * @param string $webspaceKey
  42. * @param string $locale
  43. *
  44. * @return array
  45. */
  46. public function loadByArea($area, $webspaceKey = null, $locale = null/*, $loadExcerpt = false */)
  47. {
  48. /** @var bool $loadExcerpt */
  49. $loadExcerpt = \func_num_args() > 3 ? \func_get_args()[3] : false;
  50. if (!$webspaceKey) {
  51. $webspaceKey = $this->requestAnalyzer->getWebspace()->getKey();
  52. }
  53. if (!$locale) {
  54. $locale = $this->requestAnalyzer->getCurrentLocalization()->getLocale();
  55. }
  56. $this->snippetAreaReferenceStore->add($area);
  57. try {
  58. $snippet = $this->defaultSnippetManager->load($webspaceKey, $area, $locale);
  59. } catch (WrongSnippetTypeException $exception) {
  60. return null;
  61. } catch (DocumentNotFoundException $exception) {
  62. return null;
  63. }
  64. if (!$snippet) {
  65. return null;
  66. }
  67. $snippets = $this->snippetResolver->resolve([$snippet->getUuid()], $webspaceKey, $locale, null, $loadExcerpt);
  68. if (!\array_key_exists(0, $snippets)) {
  69. return null;
  70. }
  71. return $snippets[0];
  72. }
  73. }