You are here

public function TwitterEmbedFormatter::viewElements in Media entity Twitter 8.2

Same name and namespace in other branches
  1. 8 src/Plugin/Field/FieldFormatter/TwitterEmbedFormatter.php \Drupal\media_entity_twitter\Plugin\Field\FieldFormatter\TwitterEmbedFormatter::viewElements()

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

src/Plugin/Field/FieldFormatter/TwitterEmbedFormatter.php, line 91

Class

TwitterEmbedFormatter
Plugin implementation of the 'twitter_embed' formatter.

Namespace

Drupal\media_entity_twitter\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $element = [];
  foreach ($items as $delta => $item) {
    $matches = [];
    foreach (Twitter::$validationRegexp as $pattern => $key) {
      if (preg_match($pattern, $this
        ->getEmbedCode($item), $item_matches)) {
        $matches[] = $item_matches;
      }
    }
    if (!empty($matches)) {
      $matches = reset($matches);
    }
    if (!empty($matches['user']) && !empty($matches['id'])) {
      $element[$delta] = [
        '#theme' => 'media_entity_twitter_tweet',
        '#path' => 'https://twitter.com/' . $matches['user'] . '/statuses/' . $matches['id'],
        '#attributes' => [
          'class' => [
            'twitter-tweet',
            'element-hidden',
          ],
          'lang' => 'en',
        ],
      ];

      // If the option was not selected to show the conversation, then pass
      // the API option to disable the conversation.
      // @see https://developer.twitter.com/en/docs/twitter-for-websites/embedded-tweets/overview
      if (!$this
        ->getSetting('conversation')) {
        $element[$delta]['#attributes']['data-conversation'] = 'none';
      }
    }
  }
  if (!empty($element)) {
    $element['#attached'] = [
      'library' => [
        'media_entity_twitter/integration',
      ],
    ];
  }
  return $element;
}