View source
<?php
namespace Drupal\fb_instant_articles\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\fb_instant_articles\Regions;
use Facebook\InstantArticles\Elements\Ad;
use Facebook\InstantArticles\Elements\Header;
use Facebook\InstantArticles\Elements\InstantArticle;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class AdFormatter extends FormatterBase {
public static function defaultSettings() {
return [
'source_type' => self::SOURCE_TYPE_URL,
'width' => 300,
'height' => 250,
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['source_type'] = [
'#type' => 'select',
'#title' => $this
->t('Source type'),
'#description' => $this
->t('Add your tracker specifying the URL or embed the full unescaped HTML'),
'#default_value' => $this
->getSetting('source_type'),
'#options' => [
self::SOURCE_TYPE_URL => $this
->t('URL'),
self::SOURCE_TYPE_HTML => $this
->t('Embedded HTML'),
],
];
$element['height'] = [
'#type' => 'number',
'#title' => $this
->t('Height'),
'#description' => $this
->t('Height of the iframe element.'),
'#default_value' => $this
->getSetting('height'),
];
$element['width'] = [
'#type' => 'number',
'#title' => $this
->t('Width'),
'#description' => $this
->t('Width of the iframe element.'),
'#default_value' => $this
->getSetting('width'),
];
return $element;
}
public function settingsSummary() {
$summary = [];
if ($source_type = $this
->getSetting('source_type')) {
$summary[] = $source_type === self::SOURCE_TYPE_URL ? $this
->t('URL') : $this
->t('Embedded HTML');
}
if ($width = $this
->getSetting('width')) {
$summary[] = $this
->t('Width: @width', [
'@width' => $width,
]);
}
if ($height = $this
->getSetting('height')) {
$summary[] = $this
->t('Height: @height', [
'@height' => $height,
]);
}
return $summary;
}
public function viewInstantArticle(FieldItemListInterface $items, InstantArticle $article, $region, NormalizerInterface $normalizer, $langcode = NULL) {
foreach ($items as $delta => $item) {
$ad = Ad::create();
if ($width = $this
->getSetting('width')) {
$ad
->withWidth((int) $width);
}
if ($height = $this
->getSetting('height')) {
$ad
->withHeight((int) $height);
}
if ($this
->getSetting('source_type') === self::SOURCE_TYPE_HTML) {
$ad
->withHTML($this
->getItemValue($item));
}
else {
$ad
->withSource($this
->getItemValue($item));
}
if ($region === Regions::REGION_HEADER) {
$header = $article
->getHeader();
if (!$header) {
$header = Header::create();
$article
->withHeader($header);
}
$header
->addAd($ad);
}
else {
$article
->addChild($ad);
}
}
}
protected function getItemValue(FieldItemInterface $item) {
return $item->value;
}
}