public function BynderVideoFormatter::viewElements in Bynder 4.0.x
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/ BynderVideoFormatter.php, line 105
Class
- BynderVideoFormatter
- Plugin implementation of the 'Bynder Video' formatter.
Namespace
Drupal\bynder\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$is_entityreference = $this->fieldDefinition
->getType() == 'entity_reference';
foreach ($items as $delta => $item) {
/** @var \Drupal\media\MediaInterface $media */
$media = $is_entityreference ? $item->entity : $items
->getEntity();
if (!$media) {
continue;
}
$source_plugin = $media
->getSource();
if ($source_plugin instanceof Bynder && ($video_preview_urls = $source_plugin
->getMetadata($media, 'videoPreviewURLs'))) {
$attributes = new Attribute();
$attributes
->setAttribute('controls', $this
->getSetting('controls'))
->setAttribute('autoplay', $this
->getSetting('autoplay'))
->setAttribute('loop', $this
->getSetting('loop'))
->setAttribute('mute', $this
->getSetting('mute'))
->setAttribute('width', $this
->getSetting('width'))
->setAttribute('height', $this
->getSetting('height'));
$source_attributes = [];
foreach ($video_preview_urls as $video_url) {
$source_attribute = new Attribute();
// If the url is relative, make it external using the account domain.
if (!preg_match('/^https?:/', $video_url)) {
$bynderSettings = $this->configFactory
->get('bynder.settings');
$accountDomain = $bynderSettings
->get('account_domain');
$accountDomain = rtrim($accountDomain, '/');
$completeUrl = "https://{$accountDomain}{$video_url}";
if (UrlHelper::isValid($completeUrl)) {
$video_url = $completeUrl;
}
}
$source_attribute
->setAttribute('src', $video_url);
// Try to get the extension from metadata.
// If unable to, get if from the filename.
// Default to mp4.
$extensionMetaData = $source_plugin
->getMetadata($media, 'extension');
$extensionType = 'mp4';
if (!empty($extensionMetaData) && !empty($extensionMetaDataValue = reset($extensionMetaData))) {
$extensionType = $extensionMetaDataValue;
}
else {
$path_info = pathinfo($video_url);
if ($path_info['extension']) {
$extensionType = $path_info['extension'];
}
}
$source_attribute
->setAttribute('type', "video/{$extensionType}");
$source_attributes[] = $source_attribute;
}
$elements[] = [
'#theme' => 'bynder_video',
'#attributes' => $attributes,
'#source_attributes' => $source_attributes,
];
}
}
return $elements;
}