You are here

public function EntityAnalyser::createEntityPreview in Real-time SEO for Drupal 8.2

Takes an entity, renders it and adds the metatag values.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity to retrieve preview data for.

Return value

array An array containing the metatag values. Additionally the url is added if available under the `url` key and `text` contains a representation of the rendered HTML.

File

src/EntityAnalyser.php, line 81

Class

EntityAnalyser
Provides a preview renderer for entities.

Namespace

Drupal\yoast_seo

Code

public function createEntityPreview(EntityInterface $entity) {
  $entity->in_preview = TRUE;
  $html = $this
    ->renderEntity($entity);
  $metatags = $this->metatagManager
    ->tagsFromEntityWithDefaults($entity);

  // Trigger hook_metatags_alter().
  // Allow modules to override tags or the entity used for token replacements.
  // Also used to override editable titles and descriptions.
  $context = [
    'entity' => $entity,
  ];
  \Drupal::service('module_handler')
    ->alter('metatags', $metatags, $context);
  $this
    ->replaceContextAwareTokens($metatags, $entity);

  // Resolve the metatags from tokens into actual values.
  $data = $this->metatagManager
    ->generateRawElements($metatags, $entity);

  // Turn our tag render array into a key => value array.
  foreach ($data as $name => $tag) {
    if (isset($tag['#attributes']['content'])) {
      $data[$name] = $tag['#attributes']['content'];
    }
    elseif (isset($tag['#attributes']['href'])) {
      $data[$name] = $tag['#attributes']['href'];
    }
  }

  // Translate some fields that have different names between metatag module
  // and the Yoast library.
  foreach ($this
    ->getFieldMappings() as $source => $target) {
    if (isset($data[$source])) {
      $data[$target] = $data[$source];
      unset($data[$source]);
    }
  }

  // Add fields that our widget displays.
  $data['title'] = $entity
    ->label();

  // An entity must be saved before it has a URL.
  $data['url'] = !$entity
    ->isNew() ? $entity
    ->toUrl()
    ->toString() : '';

  // Add our HTML as analyzable text (Yoast will sanitize).
  $data['text'] = $html
    ->__toString();
  return $data;
}