You are here

public function AdFormatter::viewInstantArticle in Facebook Instant Articles 3.x

Same name and namespace in other branches
  1. 8.2 src/Plugin/Field/FieldFormatter/AdFormatter.php \Drupal\fb_instant_articles\Plugin\Field\FieldFormatter\AdFormatter::viewInstantArticle()

Modifies the given instant article with the contents of this field.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

\Facebook\InstantArticles\Elements\InstantArticle $article: Instant article object to modify, rendering the contents of this field into it.

string $region: The Instant Article region name that the contents of this field should be rendered into.

\Symfony\Component\Serializer\Normalizer\NormalizerInterface $normalizer: Normalizer in case the formatter needs to recursively normalize, eg. in the case of a entity reference field.

string $langcode: (optional) The language that should be used to render the field. Defaults to the current content language.

Overrides InstantArticleFormatterInterface::viewInstantArticle

File

src/Plugin/Field/FieldFormatter/AdFormatter.php, line 88

Class

AdFormatter
Plugin implementation of the 'fbia_ad' formatter.

Namespace

Drupal\fb_instant_articles\Plugin\Field\FieldFormatter

Code

public function viewInstantArticle(FieldItemListInterface $items, InstantArticle $article, $region, NormalizerInterface $normalizer, $langcode = NULL) {
  foreach ($items as $delta => $item) {

    // Create the ad object according to the field settings.
    $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));
    }

    // Ad the ad to the appropriate region.
    if ($region === Regions::REGION_HEADER) {
      $header = $article
        ->getHeader();
      if (!$header) {
        $header = Header::create();
        $article
          ->withHeader($header);
      }
      $header
        ->addAd($ad);
    }
    else {
      $article
        ->addChild($ad);
    }
  }
}