View source
<?php
namespace Drupal\oembed\Plugin\Field\FieldFormatter;
use Bangpound\oEmbed\Consumer;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Render\Markup;
use Symfony\Component\DependencyInjection\ContainerInterface;
class oEmbedLinkFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
private $consumer;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, Consumer $consumer) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->consumer = $consumer;
}
public static function defaultSettings() {
return array(
'maxwidth' => '',
'maxheight' => '',
) + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$form = parent::settingsForm($form, $form_state);
$form['maxwidth'] = [
'#type' => 'textfield',
'#title' => $this
->t('Maximum Width'),
'#default_value' => $this
->getSetting('maxwidth'),
];
$form['maxheight'] = [
'#type' => 'textfield',
'#title' => $this
->t('Maximum Height'),
'#default_value' => $this
->getSetting('maxheight'),
];
return $form;
}
public function settingsSummary() {
$summary = parent::settingsSummary();
if ($maxwidth = $this
->getSetting('maxwidth')) {
$summary[] = $this
->t('Max Width: @maxwidth', array(
'@maxwidth' => $maxwidth,
));
}
if ($maxheight = $this
->getSetting('maxheight')) {
$summary[] = $this
->t('Max Height: @maxheight', array(
'@maxheight' => $maxheight,
));
}
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
$output = $this->consumer
->get($item
->getUrl()
->getUri(), $this
->getSettings());
$elements[$delta] = [
'#markup' => Markup::create((string) $output),
];
}
return $elements;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$consumer = $container
->get('oembed.consumer');
return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['view_mode'], $configuration['third_party_settings'], $consumer);
}
}