TwitterEmbedFormatter.php in Media entity Twitter 8
File
src/Plugin/Field/FieldFormatter/TwitterEmbedFormatter.php
View source
<?php
namespace Drupal\media_entity_twitter\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\media_entity_twitter\Plugin\MediaEntity\Type\Twitter;
class TwitterEmbedFormatter extends FormatterBase {
protected function getEmbedCode(FieldItemInterface $item) {
switch ($item
->getFieldDefinition()
->getType()) {
case 'link':
return $item->uri;
case 'string':
case 'string_long':
return $item->value;
default:
break;
}
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = array();
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',
],
'data-conversation' => 'none',
'lang' => 'en',
],
];
}
}
if (!empty($element)) {
$element['#attached'] = [
'library' => [
'media_entity_twitter/integration',
],
];
}
return $element;
}
}