You are here

class JsonFeedFields in JSON Feed 8

Plugin which displays fields for a JSON feed.

Plugin annotation


@ViewsRow(
  id = "json_feed_fields",
  title = @Translation("JSON fields"),
  help = @Translation("Display fields as JSON items."),
  display_types = {"json_feed"}
)

Hierarchy

Expanded class hierarchy of JsonFeedFields

File

src/Plugin/views/row/JsonFeedFields.php, line 19

Namespace

Drupal\json_feed\Plugin\views\row
View source
class JsonFeedFields extends RowPluginBase {

  /**
   * Does the row plugin support to add fields to it's output.
   *
   * @var bool
   */
  protected $usesFields = TRUE;

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['id'] = [
      'default' => '',
    ];
    $options['url'] = [
      'default' => '',
    ];
    $options['title'] = [
      'default' => '',
    ];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $initial_labels = [
      '' => $this
        ->t('- None -'),
    ];
    $view_fields_labels = $this->displayHandler
      ->getFieldLabels();
    $view_fields_labels = array_merge($initial_labels, $view_fields_labels);
    $form['id_field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('id attribute'),
      '#description' => $this
        ->t('Unique identifier for this item over time.'),
      '#options' => $view_fields_labels,
      '#default_value' => $this->options['id_field'],
      '#required' => TRUE,
    ];
    $form['url_field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('url attribute'),
      '#description' => $this
        ->t('Permanent link to this item.'),
      '#options' => $view_fields_labels,
      '#default_value' => $this->options['url_field'],
      '#required' => TRUE,
    ];
    $form['external_url_field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('external_url attribute'),
      '#description' => $this
        ->t('URL of a page elsewhere that this item is referencing.'),
      '#options' => $view_fields_labels,
      '#default_value' => $this->options['external_url_field'],
    ];
    $form['title_field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('title attribute'),
      '#description' => $this
        ->t('JSON title attribute. This must be plain text, not linked to the content.'),
      '#options' => $view_fields_labels,
      '#default_value' => $this->options['title_field'],
    ];
    $form['content_html_field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('content_html attribute'),
      '#description' => $this
        ->t('JSON content_html attribute. This is the only attribute in the JSON Feed spec that allows HTML.'),
      '#options' => $view_fields_labels,
      '#default_value' => $this->options['content_html_field'],
    ];
    $form['content_text_field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('content_text attribute'),
      '#description' => $this
        ->t('JSON content_text attribute.'),
      '#options' => $view_fields_labels,
      '#default_value' => $this->options['content_text_field'],
    ];
    $form['summary_field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('summary attribute'),
      '#description' => $this
        ->t('JSON summary attribute. This must be plain text.'),
      '#options' => $view_fields_labels,
      '#default_value' => $this->options['summary_field'],
    ];
    $form['image_field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('image attribute'),
      '#description' => $this
        ->t('The URL of the main image for the item. Feed readers may use the image as a preview.'),
      '#options' => $view_fields_labels,
      '#default_value' => $this->options['image_field'],
    ];
    $form['banner_image_field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('banner image attribute'),
      '#description' => $this
        ->t('The URL of an image to use as a banner. A feed reader with a detail view may choose to show this banner image at the top of the detail view, possibly with the title overlaid.'),
      '#options' => $view_fields_labels,
      '#default_value' => $this->options['banner_image_field'],
    ];
    $form['date_published_field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('date_published attribute'),
      '#description' => $this
        ->t("JSON date_published attribute, formatted as RFC 3339 (Y-m-d\\TH:i:sP)"),
      '#options' => $view_fields_labels,
      '#default_value' => $this->options['date_published_field'],
    ];
    $form['date_modified_field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('date_modified attribute'),
      '#description' => $this
        ->t("JSON date_modified attribute, formatted as RFC 3339 (Y-m-d\\TH:i:sP)"),
      '#options' => $view_fields_labels,
      '#default_value' => $this->options['date_modified_field'],
    ];
    $form['tags_field'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('tags attribute'),
      '#description' => $this
        ->t("JSON tags attribute. Accepts a comma separated list of tag names."),
      '#options' => $view_fields_labels,
      '#default_value' => $this->options['tags_field'],
    ];
    $form['author'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Author'),
      '#open' => TRUE,
    ];
    $form['author_name_field'] = [
      '#fieldset' => 'author',
      '#type' => 'select',
      '#title' => $this
        ->t('item author name attribute'),
      '#description' => $this
        ->t("JSON author name attribute."),
      '#options' => $view_fields_labels,
      '#default_value' => $this->options['author_name_field'],
    ];
    $form['author_url_field'] = [
      '#fieldset' => 'author',
      '#type' => 'select',
      '#title' => $this
        ->t('item author url attribute'),
      '#description' => $this
        ->t("The URL of a site owned by the item's author."),
      '#options' => $view_fields_labels,
      '#default_value' => $this->options['author_url_field'],
    ];
    $form['author_avatar_field'] = [
      '#fieldset' => 'author',
      '#type' => 'select',
      '#title' => $this
        ->t('item author avatar attribute'),
      '#description' => $this
        ->t("The URL for an image for the item's author."),
      '#options' => $view_fields_labels,
      '#default_value' => $this->options['author_avatar_field'],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function validate() {
    $errors = parent::validate();
    $required_options = [
      'id_field',
      'url_field',
    ];
    foreach ($required_options as $required_option) {
      if (empty($this->options[$required_option])) {
        $errors[] = $this
          ->t('Row style plugin requires specifying which views fields to use for JSON feed item.');
        break;
      }
    }

    // Ensure either content_html_field or content_text_field is set, one or the
    // other is required.
    if (empty($this->options['content_html_field']) && empty($this->options['content_text_field'])) {
      $errors[] = $this
        ->t('Either content_html or content_text must have a value.');
    }
    return $errors;
  }

  /**
   * {@inheritdoc}
   */
  public function render($row) {

    // Create the JSON item.
    $item = [];
    $row_index = $this->view->row_index;
    $item['id'] = strip_tags($this
      ->getField($row_index, $this->options['id_field']));
    $item['url'] = strip_tags($this
      ->getAbsoluteUrlForField($row_index, 'url_field'));
    $item['external_url'] = strip_tags($this
      ->getAbsoluteUrlForField($row_index, 'external_url_field'));
    $item['title'] = strip_tags($this
      ->getField($row_index, $this->options['title_field']));
    $item['content_html'] = $this
      ->getField($row_index, $this->options['content_html_field']);
    $item['content_text'] = strip_tags($this
      ->getField($row_index, $this->options['content_text_field']));
    $item['summary'] = strip_tags($this
      ->getField($row_index, $this->options['summary_field']));
    $item['image'] = strip_tags($this
      ->getAbsoluteUrlForField($row_index, 'image_field'));
    $item['banner_image'] = strip_tags($this
      ->getAbsoluteUrlForField($row_index, 'banner_image_field'));
    $item['date_published'] = strip_tags($this
      ->getField($row_index, $this->options['date_published_field']));
    $item['date_modified'] = strip_tags($this
      ->getField($row_index, $this->options['date_modified_field']));
    $item['author'] = array_map('strip_tags', $this
      ->getAuthor($row_index, $this->options));
    $item['tags'] = array_map('strip_tags', $this
      ->getTags($row_index, $this->options['tags_field']));

    // Remove empty attributes.
    $item['author'] = array_filter($item['author']);
    $item = array_filter($item);
    return $item;
  }

  /**
   * Retrieves a views field value from the style plugin.
   *
   * @param int $index
   *   The index count of the row as expected by views_plugin_style::getField().
   * @param string $field_id
   *   The ID assigned to the required field in the display.
   *
   * @return string
   *   The rendered field value.
   */
  public function getField($index, $field_id) {
    if (empty($this->view->style_plugin) || !is_object($this->view->style_plugin) || empty($field_id)) {
      return '';
    }
    return (string) $this->view->style_plugin
      ->getField($index, $field_id);
  }

  /**
   * If the field value exists, return it as an absolute URL.
   *
   * @param int $row_index
   *   The index count of the row as expected by views_plugin_style::getField().
   * @param string $field_id
   *   The ID assigned to the required field in the display.
   *
   * @return null|string
   *   The absolute URL for the field's value.
   */
  protected function getAbsoluteUrlForField($row_index, $field_id) {
    if (isset($this->options[$field_id])) {
      $field_value = $this
        ->getField($row_index, $this->options[$field_id]);
      if (strpos($field_value, '/') !== 0) {
        $field_value = '/' . $field_value;
      }
      return Url::fromUserInput($field_value)
        ->setAbsolute()
        ->toString();
    }
    return NULL;
  }

  /**
   * Retrieve and format tag attribute values.
   *
   * @param int $row_index
   *   The index count of the row as expected by views_plugin_style::getField().
   * @param string $field_id
   *   The ID assigned to the required field in the display.
   *
   * @return array
   *   An array of tag strings.
   */
  protected function getTags($row_index, $field_id) {
    $tags_csv = $this
      ->getField($row_index, $field_id);
    return array_map('trim', explode(',', $tags_csv));
  }

  /**
   * Retrieve and format author attribute values.
   *
   * @param int $row_index
   *   The index count of the row as expected by views_plugin_style::getField().
   * @param array $options
   *   The full options array which contains author field configurations.
   *
   * @return array
   *   An array of author attributes.
   */
  protected function getAuthor($row_index, array $options) {
    return [
      'name' => $this
        ->getField($row_index, $options['author_name_field']),
      'url' => $this
        ->getAbsoluteUrlForField($row_index, $options['author_url_field']),
      'avatar' => $this
        ->getField($row_index, $options['author_avatar_field']),
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
JsonFeedFields::$usesFields protected property Does the row plugin support to add fields to it's output. Overrides RowPluginBase::$usesFields
JsonFeedFields::buildOptionsForm public function Provide a form for setting options. Overrides RowPluginBase::buildOptionsForm
JsonFeedFields::defineOptions protected function Information about options for all kinds of purposes will be held here. Overrides RowPluginBase::defineOptions
JsonFeedFields::getAbsoluteUrlForField protected function If the field value exists, return it as an absolute URL.
JsonFeedFields::getAuthor protected function Retrieve and format author attribute values.
JsonFeedFields::getField public function Retrieves a views field value from the style plugin.
JsonFeedFields::getTags protected function Retrieve and format tag attribute values.
JsonFeedFields::render public function Render a row object. This usually passes through to a theme template of some form, but not always. Overrides RowPluginBase::render
JsonFeedFields::validate public function Validate that the plugin is correct and can be saved. Overrides PluginBase::validate
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$definition public property Plugins's definition
PluginBase::$displayHandler public property The display object this plugin is for.
PluginBase::$options public property Options for this plugin will be held here.
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::$renderer protected property Stores the render API renderer. 3
PluginBase::$view public property The top object of a view. 1
PluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 14
PluginBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 62
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::destroy public function Clears a plugin. Overrides ViewsPluginInterface::destroy 2
PluginBase::doFilterByDefinedOptions protected function Do the work to filter out stored options depending on the defined options.
PluginBase::filterByDefinedOptions public function Filter out stored options depending on the defined options. Overrides ViewsPluginInterface::filterByDefinedOptions
PluginBase::getAvailableGlobalTokens public function Returns an array of available token replacements. Overrides ViewsPluginInterface::getAvailableGlobalTokens
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::getProvider public function Returns the plugin provider. Overrides ViewsPluginInterface::getProvider
PluginBase::getRenderer protected function Returns the render API renderer. 1
PluginBase::globalTokenForm public function Adds elements for available core tokens to a form. Overrides ViewsPluginInterface::globalTokenForm
PluginBase::globalTokenReplace public function Returns a string with any core tokens replaced. Overrides ViewsPluginInterface::globalTokenReplace
PluginBase::INCLUDE_ENTITY constant Include entity row languages when listing languages.
PluginBase::INCLUDE_NEGOTIATED constant Include negotiated languages when listing languages.
PluginBase::init public function Initialize the plugin. Overrides ViewsPluginInterface::init 8
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::listLanguages protected function Makes an array of languages, optionally including special languages.
PluginBase::pluginTitle public function Return the human readable name of the display. Overrides ViewsPluginInterface::pluginTitle
PluginBase::preRenderAddFieldsetMarkup public static function Moves form elements into fieldsets for presentation purposes. Overrides ViewsPluginInterface::preRenderAddFieldsetMarkup
PluginBase::preRenderFlattenData public static function Flattens the structure of form elements. Overrides ViewsPluginInterface::preRenderFlattenData
PluginBase::queryLanguageSubstitutions public static function Returns substitutions for Views queries for languages.
PluginBase::setOptionDefaults protected function Fills up the options of the plugin with defaults.
PluginBase::summaryTitle public function Returns the summary of the settings in the display. Overrides ViewsPluginInterface::summaryTitle 6
PluginBase::themeFunctions public function Provide a full list of possible theme templates used by this style. Overrides ViewsPluginInterface::themeFunctions 1
PluginBase::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks 6
PluginBase::unpackOptions public function Unpack options over our existing defaults, drilling down into arrays so that defaults don't get totally blown away. Overrides ViewsPluginInterface::unpackOptions
PluginBase::usesOptions public function Returns the usesOptions property. Overrides ViewsPluginInterface::usesOptions 8
PluginBase::viewsTokenReplace protected function Replaces Views' tokens in a given string. The resulting string will be sanitized with Xss::filterAdmin. 1
PluginBase::VIEWS_QUERY_LANGUAGE_SITE_DEFAULT constant Query string to indicate the site default language.
PluginBase::__construct public function Constructs a PluginBase object. Overrides PluginBase::__construct
RowPluginBase::$usesOptions protected property Denotes whether the plugin has an additional options form. Overrides PluginBase::$usesOptions 1
RowPluginBase::preRender public function Allow the style to do stuff before each row is rendered. 4
RowPluginBase::query public function Add anything to the query that we might need to. Overrides PluginBase::query 2
RowPluginBase::submitOptionsForm public function Perform any necessary changes to the form values prior to storage. There is no need for this function to actually store the data. Overrides PluginBase::submitOptionsForm 1
RowPluginBase::usesFields public function Returns the usesFields property. 4
RowPluginBase::validateOptionsForm public function Validate the options form. Overrides PluginBase::validateOptionsForm 1
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.