<?php

namespace Drupal\pagedesigner_yoast\Plugin\Field\FieldFormatter;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;

/**
 * Plugin implementation of the 'description_value' formatter.
 *
 * @FieldFormatter(
 *   id = "pagedesigner_yoast_metatag_description",
 *   label = @Translation("Description Value"),
 *   field_types = {
 *    "metatag",
 *   }
 * )
 */
class DescriptionFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    foreach ($items as $delta => $item) {
      $value = '';
      if (!empty($item->getValue()['value'])) {
        $value = Json::decode($item->getValue()['value']);
        if (!$value) {
          $value = @unserialize($item->getValue()['value'], ['allowed_classes' => FALSE]);
          if ($item->getValue()['value'] !== 'b:0;' && $value === FALSE) {
            $value = '';
          }
        }
      }
      $description = (empty($value['description'])) ? '' : $value['description'];
      $elements[$delta] = [
        '#markup' => $description,
      ];
    }
    return $elements;
  }

}
