class DefaultProcessor

You are here

Defines a default processor implementation.

Creates lightweight records from feed items.

Plugin annotation

@AggregatorProcessor(
  id = "aggregator",
  title = @Translation("Default processor"),
  description = @Translation("Creates lightweight records from feed items.")
)

Namespace

Drupal\aggregator\Plugin\aggregator\processor

Hierarchy

Expanded class hierarchy of DefaultProcessor

Members

Contains filters are case sensitive
Namesort descending Modifiers Type Description
AggregatorPluginSettingsBase::defaultConfiguration public function Returns default configuration for this plugin. Overrides ConfigurablePluginInterface::defaultConfiguration
AggregatorPluginSettingsBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
DefaultProcessor::$configFactory protected property Contains the configuration object factory.
DefaultProcessor::$itemQuery protected property The entity query object for feed items.
DefaultProcessor::$itemStorage protected property The entity storage for items.
DefaultProcessor::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
DefaultProcessor::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
DefaultProcessor::delete public function Deletes stored feed data. Overrides ProcessorInterface::delete
DefaultProcessor::getConfiguration public function Returns this plugin's configuration. Overrides ConfigurablePluginInterface::getConfiguration
DefaultProcessor::postProcess public function Implements \Drupal\aggregator\Plugin\ProcessorInterface::postProcess(). Overrides ProcessorInterface::postProcess
DefaultProcessor::process public function Processes feed data. Overrides ProcessorInterface::process
DefaultProcessor::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurablePluginInterface::setConfiguration
DefaultProcessor::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm
DefaultProcessor::__construct public function Constructs a DefaultProcessor object. Overrides PluginBase::__construct
PluginBase::$configuration protected property Configuration information passed into the plugin.
PluginBase::$pluginDefinition protected property The plugin implementation definition.
PluginBase::$pluginId protected property The plugin_id.
PluginBase::$translationManager protected property The translation manager service.
PluginBase::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBasePluginId public function Returns the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBasePluginId
PluginBase::getDerivativeId public function Returns the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Returns the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition
PluginBase::getPluginId public function Returns the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::setTranslationManager public function Sets the translation manager for this plugin.
PluginBase::t protected function Translates a string to the current language or to a given language.
PluginBase::translationManager protected function Gets the translation manager.
PluginBase::__sleep public function @todo Remove when Drupal\Core\DependencyInjection\DependencySerialization is converted to a trait.
PluginBase::__wakeup public function @todo Remove when Drupal\Core\DependencyInjection\DependencySerialization is converted to a trait.

File

core/modules/aggregator/lib/Drupal/aggregator/Plugin/aggregator/processor/DefaultProcessor.php, line 31
Contains \Drupal\aggregator\Plugin\aggregator\processor\DefaultProcessor.

View source
class DefaultProcessor extends AggregatorPluginSettingsBase implements ProcessorInterface, ContainerFactoryPluginInterface {

  /**
   * Contains the configuration object factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The entity query object for feed items.
   *
   * @var \Drupal\Core\Entity\Query\QueryInterface
   */
  protected $itemQuery;

  /**
   * The entity storage for items.
   *
   * @var \Drupal\aggregator\ItemStorageInterface
   */
  protected $itemStorage;

  /**
   * Constructs a DefaultProcessor object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config
   *   The configuration factory object.
   * @param \Drupal\Core\Entity\Query\QueryInterface $item_query
   *   The entity query object for feed items.
   * @param \Drupal\aggregator\ItemStorageInterface $item_storage
   *   The entity storage for feed items.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config, QueryInterface $item_query, ItemStorageInterface $item_storage) {
    $this->configFactory = $config;
    $this->itemStorage = $item_storage;
    $this->itemQuery = $item_query;
    // @todo Refactor aggregator plugins to ConfigEntity so merging
    //   the configuration here is not needed.
    parent::__construct($configuration + $this->getConfiguration(), $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container->get('config.factory'), $container->get('entity.query')->get('aggregator_item'), $container->get('entity.manager')->getStorage('aggregator_item'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, array &$form_state) {
    $processors = $this->configuration['processors'];
    $info = $this->getPluginDefinition();
    $counts = array(
      3,
      5,
      10,
      15,
      20,
      25,
    );
    $items = array_map(function($count) {
      return format_plural($count, '1 item', '@count items');
    }, array_combine($counts, $counts));
    $intervals = array(
      3600,
      10800,
      21600,
      32400,
      43200,
      86400,
      172800,
      259200,
      604800,
      1209600,
      2419200,
      4838400,
      9676800,
    );
    $period = array_map('format_interval', array_combine($intervals, $intervals));
    $period[AGGREGATOR_CLEAR_NEVER] = t('Never');

    $form['processors'][$info['id']] = array();
    // Only wrap into details if there is a basic configuration.
    if (isset($form['basic_conf'])) {
      $form['processors'][$info['id']] = array(
        '#type' => 'details',
        '#title' => t('Default processor settings'),
        '#description' => $info['description'],
        '#open' => in_array($info['id'], $processors),
      );
    }

    $form['processors'][$info['id']]['aggregator_summary_items'] = array(
      '#type' => 'select',
      '#title' => t('Number of items shown in listing pages'),
      '#default_value' => $this->configuration['source']['list_max'],
      '#empty_value' => 0,
      '#options' => $items,
    );

    $form['processors'][$info['id']]['aggregator_clear'] = array(
      '#type' => 'select',
      '#title' => t('Discard items older than'),
      '#default_value' => $this->configuration['items']['expire'],
      '#options' => $period,
      '#description' => t('Requires a correctly configured <a href="@cron">cron maintenance task</a>.', array('@cron' => url('admin/reports/status'))),
    );

    $lengths = array(
      0,
      200,
      400,
      600,
      800,
      1000,
      1200,
      1400,
      1600,
      1800,
      2000,
    );
    $options = array_map(function($length) {
      return ($length == 0) ? t('Unlimited') : format_plural($length, '1 character', '@count characters');
    }, array_combine($lengths, $lengths));

    $form['processors'][$info['id']]['aggregator_teaser_length'] = array(
      '#type' => 'select',
      '#title' => t('Length of trimmed description'),
      '#default_value' => $this->configuration['items']['teaser_length'],
      '#options' => $options,
      '#description' => t('The maximum number of characters used in the trimmed version of content.'),
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, array &$form_state) {
    $this->configuration['items']['expire'] = $form_state['values']['aggregator_clear'];
    $this->configuration['items']['teaser_length'] = $form_state['values']['aggregator_teaser_length'];
    $this->configuration['source']['list_max'] = $form_state['values']['aggregator_summary_items'];
    // @todo Refactor aggregator plugins to ConfigEntity so this is not needed.
    $this->setConfiguration($this->configuration);
  }

  /**
   * {@inheritdoc}
   */
  public function process(FeedInterface $feed) {
    if (!is_array($feed->items)) {
      return;
    }
    foreach ($feed->items as $item) {
      // @todo: The default entity view builder always returns an empty
      //   array, which is ignored in aggregator_save_item() currently. Should
      //   probably be fixed.
      if (empty($item['title'])) {
        continue;
      }

      // Save this item. Try to avoid duplicate entries as much as possible. If
      // we find a duplicate entry, we resolve it and pass along its ID is such
      // that we can update it if needed.
      if (!empty($item['guid'])) {
        $values = array(
          'fid' => $feed->id(),
          'guid' => $item['guid'],
        );
      }
      elseif ($item['link'] && $item['link'] != $feed->link && $item['link'] != $feed->url) {
        $values = array(
          'fid' => $feed->id(),
          'link' => $item['link'],
        );
      }
      else {
        $values = array(
          'fid' => $feed->id(),
          'title' => $item['title'],
        );
      }

      // Try to load an existing entry.
      if ($entry = entity_load_multiple_by_properties('aggregator_item', $values)) {
        $entry = reset($entry);
      }
      else {
        $entry = entity_create('aggregator_item', array('langcode' => $feed->language()->id));
      }
      if ($item['timestamp']) {
        $entry->setPostedTime($item['timestamp']);
      }

      // Make sure the item title and author fit in the 255 varchar column.
      $entry->setTitle(truncate_utf8($item['title'], 255, TRUE, TRUE));
      $entry->setAuthor(truncate_utf8($item['author'], 255, TRUE, TRUE));

      $entry->setFeedId($feed->id());
      $entry->setLink($item['link']);
      $entry->setGuid($item['guid']);

      $description = '';
      if (!empty($item['description'])) {
        $description = $item['description'];
      }
      $entry->setDescription($description);

      $entry->save();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function delete(FeedInterface $feed) {
    if ($items = $this->itemStorage->loadByFeed($feed->id())) {
      $this->itemStorage->delete($items);
    }
    // @todo This should be moved out to caller with a different message maybe.
    drupal_set_message(t('The news items from %site have been deleted.', array('%site' => $feed->label())));
  }

  /**
   * Implements \Drupal\aggregator\Plugin\ProcessorInterface::postProcess().
   *
   * Expires items from a feed depending on expiration settings.
   */
  public function postProcess(FeedInterface $feed) {
    $aggregator_clear = $this->configuration['items']['expire'];

    if ($aggregator_clear != AGGREGATOR_CLEAR_NEVER) {
      // Delete all items that are older than flush item timer.
      $age = REQUEST_TIME - $aggregator_clear;
      $result = $this->itemQuery->condition('fid', $feed->id())->condition('timestamp', $age, '<')->execute();
      if ($result) {
        $entities = $this->itemStorage->loadMultiple($result);
        $this->itemStorage->delete($entities);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getConfiguration() {
    return $this->configFactory->get('aggregator.settings')->get();
  }

  /**
   * {@inheritdoc}
   */
  public function setConfiguration(array $configuration) {
    $config = $this->configFactory->get('aggregator.settings');
    foreach ($configuration as $key => $value) {
      $config->set($key, $value);
    }
    $config->save();
  }

}