AuthorReferenceFormatter.php in Facebook Instant Articles 8.2
File
src/Plugin/Field/FieldFormatter/AuthorReferenceFormatter.php
View source
<?php
namespace Drupal\fb_instant_articles\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\fb_instant_articles\Plugin\Field\InstantArticleFormatterInterface;
use Drupal\user\Plugin\Field\FieldFormatter\AuthorFormatter as DrupalAuthorFormatter;
use Facebook\InstantArticles\Elements\Author;
use Facebook\InstantArticles\Elements\Header;
use Facebook\InstantArticles\Elements\InstantArticle;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class AuthorReferenceFormatter extends DrupalAuthorFormatter implements InstantArticleFormatterInterface {
public static function defaultSettings() {
return [
'link' => TRUE,
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements['link'] = [
'#title' => t('Link author to the referenced entity'),
'#type' => 'checkbox',
'#default_value' => $this
->getSetting('link'),
];
return $elements;
}
public function settingsSummary() {
$summary = [];
$summary[] = $this
->getSetting('link') ? t('Link to the referenced entity') : t('No link');
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
return [];
}
public function viewInstantArticle(FieldItemListInterface $items, InstantArticle $article, $region, NormalizerInterface $normalizer, $langcode = NULL) {
$this
->prepareView([
$items
->getEntity()
->id() => $items,
]);
foreach ($this
->getEntitiesToView($items, $langcode) as $delta => $entity) {
$author = Author::create()
->withName($entity
->getDisplayName());
if ($this
->getSetting('link')) {
$author
->withURL($entity
->toUrl('canonical', [
'absolute' => TRUE,
])
->toString());
}
$header = $article
->getHeader();
if (!$header) {
$header = Header::create();
}
$header
->addAuthor($author);
}
}
}