You are here

protected function ThunderGqlsRenderer::jsonld in Thunder 6.2.x

Generate the jsonld string for current route.

Return value

string The jsonld string.

1 call to ThunderGqlsRenderer::jsonld()
ThunderGqlsRenderer::renderResponse in modules/thunder_gqls/src/Render/MainContent/ThunderGqlsRenderer.php
Renders the main content render array into a response.

File

modules/thunder_gqls/src/Render/MainContent/ThunderGqlsRenderer.php, line 134

Class

ThunderGqlsRenderer
Thunder GraphQL Schema content renderer.

Namespace

Drupal\thunder_gqls\Render\MainContent

Code

protected function jsonld() : string {

  // If nothing was passed in, assume the current entity.
  // @see schema_metatag_entity_load() to understand why this works.
  if (!$this->moduleHandler
    ->moduleExists('schema_metatag')) {
    return '';
  }
  $entity = metatag_get_route_entity();
  if (!$entity instanceof ContentEntityInterface) {
    return '';
  }

  // Get all the metatags for this entity.
  $metatags = [];
  foreach ($this->metatagManager
    ->tagsFromEntityWithDefaults($entity) as $tag => $data) {
    $metatags[$tag] = $data;
  }

  // Trigger hook_metatags_alter().
  // Allow modules to override tags or the entity used for token replacements.
  $context = [
    'entity' => $entity,
  ];
  $this->moduleHandler
    ->alter('metatags', $metatags, $context);
  $elements = $this->metatagManager
    ->generateElements($metatags, $entity);
  $context = new RenderContext();
  $jsonldString = $this->renderer
    ->executeInRenderContext($context, function () use ($elements) {

    // Parse the Schema.org metatags out of the array.
    if ($items = SchemaMetatagManager::parseJsonld($elements['#attached']['html_head'])) {

      // Encode the Schema.org metatags as JSON LD.
      if ($jsonld = SchemaMetatagManager::encodeJsonld($items)) {

        // Pass back the rendered result.
        $html = SchemaMetatagManager::renderArrayJsonLd($jsonld);
        return $this->renderer
          ->render($html);
      }
    }
  });
  return $jsonldString ?? '';
}