vendor/elements/json-ld-reloaded-bundle/src/Twig/JsonLdExtension.php line 56

Open in your IDE?
  1. <?php
  2. namespace Elements\Bundle\JsonLdReloadedBundle\Twig;
  3. use Elements\Bundle\JsonLdReloadedBundle\JsonLd\TemplateRenderer;
  4. use Pimcore\Db;
  5. use Pimcore\Model\DataObject\AbstractObject;
  6. use Pimcore\Model\Document;
  7. use Pimcore\Tool;
  8. use Pimcore\Log\ApplicationLogger;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\RequestStack;
  11. use Twig\Environment;
  12. use Twig\Extension\AbstractExtension;
  13. use Twig\Markup;
  14. use Twig\TwigFunction;
  15. class JsonLdExtension extends AbstractExtension
  16. {
  17.     /**
  18.      * @var Environment
  19.      */
  20.     private $twig;
  21.     /**
  22.      * @var Request|null
  23.      */
  24.     private $request;
  25.     /**
  26.      * @var TemplateRenderer
  27.      */
  28.     private $templateRenderer;
  29.     /**
  30.      * @var TemplateRenderer
  31.      */
  32.     private $disableDocumentOutput;
  33.     /**
  34.      * @var ApplicationLogger
  35.      */
  36.     private $logger;
  37.     const COMPONENT_NAME 'ElementsJsonLdReloadedBundle';
  38.     /**
  39.      * Extension constructor.
  40.      * @param Environment $twig
  41.      * @param RequestStack $requestStack
  42.      * @param TemplateRenderer $templateRenderer
  43.      */
  44.     public function __construct(Environment $twigRequestStack $requestStackTemplateRenderer $templateRendererApplicationLogger $logger)
  45.     {
  46.         $this->twig $twig;
  47.         $this->request $requestStack->getMasterRequest();
  48.         $this->templateRenderer $templateRenderer;
  49.         $this->disableDocumentOutput false;
  50.         $this->logger $logger;
  51.     }
  52.     public function getFunctions()
  53.     {
  54.         return [
  55.             new TwigFunction('jld_root', [$this'jsonLdReloadedRoot'], ['is_safe' => ['html']]),
  56.             new TwigFunction('jld_document', [$this'jsonLdReloadedRootDocument'], ['is_safe' => ['html']]),
  57.             new TwigFunction('jld', [$this'jsonLdReloaded'], ['is_safe' => ['html']]),
  58.             new TwigFunction('jld_disableDocumentOutput', [$this'setDisableDocumentOutput'], ['is_safe' => ['html']]),
  59.         ];
  60.     }
  61.     public function jsonLdReloadedRoot($object)
  62.     {
  63.         return new Markup(
  64.             sprintf('<script type="application/ld+json">%s</script>'$this->jsonLdReloaded($objecttrue)),
  65.             'UTF-8'
  66.         );
  67.     }
  68.     public function jsonLdReloadedRootDocument($document)
  69.     {
  70.         $documentProperties $document->getProperties();
  71.         $possibleProperties $this->getJsonLdProperties();
  72.         $jsonLdString '';
  73.         if (!$this->disableDocumentOutput) {
  74.             $isStaticRoute $this->request?->get('pimcore_request_source') === 'staticroute';
  75.             foreach ($possibleProperties as $propertyName) {
  76.                 if ($isStaticRoute && array_key_exists($propertyName$documentProperties) && !$documentProperties[$propertyName]->getInheritable()) {
  77.                     continue;
  78.                 }
  79.                 if (intval($document->getProperty($propertyName))) {
  80.                     if ($templateString $this->getJsonLdByTemplateId(intval($document->getProperty($propertyName)), $document)) {
  81.                         $jsonLdString .= sprintf('<script type="application/ld+json">%s</script>'$templateString);
  82.                     }
  83.                 }
  84.             }
  85.         }
  86.         return new Markup(
  87.             $jsonLdString,
  88.             'UTF-8'
  89.         );
  90.     }
  91.     /**
  92.      * @param $object
  93.      * @param bool $isRoot - wraps jsonld in script tag
  94.      * @param bool $prettyPrint - nicely formats the jsonld script
  95.      * @return Markup
  96.      */
  97.     public function jsonLdReloaded($objectbool $isRoot falsebool $prettyPrint false$showErrors false)
  98.     {
  99.         $canInherit AbstractObject::getGetInheritedValues();
  100.         AbstractObject::setGetInheritedValues(true);
  101.         try {
  102.             $jsonLd $this->templateRenderer->render($object, [
  103.                 '__path' => $this->request $this->request->getPathInfo() : '',
  104.                 '__url' => Tool::getHostUrl() . ($this->request $this->request->getRequestUri() : ''),
  105.                 'isRoot' => $isRoot
  106.             ]);
  107.         } catch (\Throwable $exception) {
  108.             // $this->logger->error($exception->getMessage() . ": " . $exception->getTraceAsString() . ': ' . $exception, ['component' => self::COMPONENT_NAME]);
  109.             // Site should not die because of jsonLD
  110.             $jsonLd '{}';
  111.             if($showErrors) {
  112.                 $jsonLd '<div class="alert alert-danger">Error while processing JsonLd: <br>' $exception->getMessage() . '</div>';
  113.             }
  114.         } finally {
  115.             AbstractObject::setGetInheritedValues($canInherit);
  116.         }
  117.         if ($prettyPrint === true) {
  118.             $json json_decode($jsonLd);
  119.             if ($json !== null) {
  120.                 $jsonLd json_encode($jsonJSON_PRETTY_PRINT);
  121.             } elseif($showErrors) { //json not valid
  122.                 $jsonLd '<div class="alert alert-danger">Json not valid: <br>' json_last_error_msg() . '</div><br>' $jsonLd;
  123.             }
  124.         }
  125.         return new Markup($jsonLd'UTF-8');
  126.     }
  127.     /**
  128.      * @param $templateId
  129.      * @param Document $document
  130.      * @return Markup
  131.      */
  132.     private function getJsonLdByTemplateId($templateIdDocument $document) {
  133.         try {
  134.             $jsonLd $this->templateRenderer->renderTemplate($templateId, [
  135.                 '__path' => $this->request $this->request->getPathInfo() : '',
  136.                 '__url' => Tool::getHostUrl() . ($this->request $this->request->getRequestUri() : ''),
  137.                 'object' => $document,
  138.                 'isRoot' => true
  139.             ]);
  140.         } catch (\Exception $exception) {
  141.             $this->logger->error($exception->getMessage() . ": " $exception->getTraceAsString() . ': ' $exception, ['component' => self::COMPONENT_NAME]);
  142.             // Site should not die because of jsonLD
  143.             $jsonLd '{}';
  144.         }
  145.         return new Markup($jsonLd'UTF-8');
  146.     }
  147.     private $jsonLDProperties = [];
  148.     private function getJsonLdProperties() {
  149.         if (empty($this->jsonLDProperties)) {
  150.             $db Db::get();
  151.             $this->jsonLDProperties $db->fetchCol('SELECT name FROM properties WHERE ctype = "document" AND name LIKE "json-ld-%" GROUP BY name');
  152.         }
  153.         return $this->jsonLDProperties;
  154.     }
  155.     /**
  156.      * @param bool $switch
  157.      */
  158.     public function setDisableDocumentOutput(bool $switch) {
  159.         $this->disableDocumentOutput $switch;
  160.     }
  161. }