AnalyticsFormatter.php in Facebook Instant Articles 8.2
File
src/Plugin/Field/FieldFormatter/AnalyticsFormatter.php
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 Facebook\InstantArticles\Elements\Analytics;
use Facebook\InstantArticles\Elements\InstantArticle;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class AnalyticsFormatter extends FormatterBase {
public static function defaultSettings() {
return [
'source_type' => self::SOURCE_TYPE_URL,
] + 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'),
],
];
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');
}
return $summary;
}
public function viewInstantArticle(FieldItemListInterface $items, InstantArticle $article, $region, NormalizerInterface $normalizer, $langcode = NULL) {
foreach ($items as $delta => $item) {
$analytics = Analytics::create();
if ($this
->getSetting('source_type') === self::SOURCE_TYPE_HTML) {
$analytics
->withHTML($this
->getItemValue($item));
}
else {
$analytics
->withSource($this
->getItemValue($item));
}
$article
->addChild($analytics);
}
}
protected function getItemValue(FieldItemInterface $item) {
return $item->value;
}
}