You are here

class RssNews in Dashboards with Layout Builder 8

Same name and namespace in other branches
  1. 2.0.x src/Plugin/Dashboard/RssNews.php \Drupal\dashboards\Plugin\Dashboard\RssNews

Show account info.

Plugin annotation


@Dashboard(
  id = "rss_news",
  label = @Translation("Show rss news"),
  category = @Translation("Informations")
)

Hierarchy

Expanded class hierarchy of RssNews

File

src/Plugin/Dashboard/RssNews.php, line 21

Namespace

Drupal\dashboards\Plugin\Dashboard
View source
class RssNews extends DashboardLazyBuildBase {

  /**
   * Default cache time.
   *
   * @var int
   */
  const CACHE_TIME = 1800;

  /**
   * Fetch rss items.
   *
   * @param string $plugin_id
   *   Plugin id for cache.
   * @param string $uri
   *   URI to fetch.
   *
   * @return array
   *   Feed items.
   */
  public static function readSource($plugin_id, $uri) : array {
    $cache = \Drupal::service('dashboards.cache');
    $cid = $plugin_id . ':' . md5($uri);
    if (!($data = $cache
      ->get($cid))) {
      Reader::setExtensionManager(\Drupal::service('feed.bridge.reader'));
      $client = \Drupal::httpClient();
      $response = $client
        ->request('GET', $uri);
      $channel = Reader::importString($response
        ->getBody()
        ->getContents());
      $items = [];
      foreach ($channel as $item) {
        $items[] = [
          'title' => $item
            ->getTitle(),
          'link' => $item
            ->getLink(),
          'description' => $item
            ->getDescription(),
          'date' => $item
            ->getDateModified()
            ->format(\DateTime::ISO8601),
        ];
      }
      $cache
        ->set($cid, $items, time() + static::CACHE_TIME);
      return $items;
    }
    return $data->data;
  }

  /**
   * {@inheritdoc}
   */
  public function buildSettingsForm(array $form, FormStateInterface $form_state, array $configuration) : array {
    $form['uri'] = [
      '#type' => 'url',
      '#title' => $this
        ->t('Feed URL or website url'),
      '#default_value' => isset($configuration['uri']) ? $configuration['uri'] : '',
    ];
    $form['max_items'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('How many items to display'),
      '#default_value' => isset($configuration['max_items']) ? $configuration['max_items'] : 5,
    ];
    $form['show_description'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show description'),
      '#default_value' => isset($configuration['show_description']) ? $configuration['show_description'] : 5,
    ];
    return $form;
  }

  /**
   * Lazy builder callback.
   *
   * @param \Drupal\dashboards\Plugin\DashboardBase $plugin
   *   Plugin id.
   * @param array $configuration
   *   Plugin configuration.
   *
   * @return array
   *   Rendering array.
   */
  public static function lazyBuild(DashboardBase $plugin, array $configuration) : array {
    $lastAccess = \Drupal::currentUser()
      ->getLastAccessedTime();
    $url = $configuration['uri'];
    $max_items = $configuration['max_items'];
    $show_description = $configuration['show_description'];

    /** @var \Drupal\Core\StringTranslation\TranslationManager $translation_manager */
    $translation_manager = \Drupal::service('string_translation');
    try {
      $items = static::readSource($plugin
        ->getPluginId(), $url);
      if (count($items) > $max_items) {
        $items = array_slice($items, 0, $max_items);
      }
      $links = [];
      foreach ($items as $item) {
        $date = new DrupalDateTime($item['date'], 'UTC');
        $newIndicator = '';
        if ($date
          ->getTimestamp() > $lastAccess) {
          $newIndicator = ' | ' . $translation_manager
            ->translate('New');
        }
        $date = \Drupal::service('date.formatter')
          ->format($date
          ->getTimestamp(), 'short');
        if ($show_description) {
          $links[] = [
            'title' => [
              '#type' => 'inline_template',
              '#template' => '<h6>{{ content }}</h6>',
              '#context' => [
                'date' => [
                  '#markup' => $item['date'],
                ],
                'content' => [
                  '#type' => 'link',
                  '#url' => Url::fromUri($item['link']),
                  '#title' => $item['title'],
                  '#attributes' => [
                    'target' => '_blank',
                  ],
                ],
              ],
            ],
            'date' => [
              '#type' => 'inline_template',
              '#template' => '<p><em>{{ date }} {{ new }}</em></p>',
              '#context' => [
                'date' => [
                  '#markup' => $date,
                ],
                'new' => [
                  '#markup' => $newIndicator,
                ],
              ],
            ],
            'description' => [
              '#type' => 'inline_template',
              '#template' => '{{ content|raw }}',
              '#context' => [
                'content' => strip_tags($item['description'], '<img> <a> <ul> <li> <p>'),
              ],
            ],
          ];
        }
        else {
          $links[] = [
            '#type' => 'inline_template',
            '#template' => '<h6>{{ content }}</h6> <em>{{ date }} {{ new }}</em>',
            '#context' => [
              'date' => [
                '#markup' => $date,
              ],
              'new' => [
                '#markup' => $newIndicator,
              ],
              'content' => [
                '#type' => 'link',
                '#url' => Url::fromUri($item['link']),
                '#title' => $item['title'],
                '#attributes' => [
                  'target' => '_blank',
                ],
              ],
            ],
          ];
        }
      }
      return [
        '#theme' => 'item_list',
        '#items' => $links,
        '#cache' => [
          'max-age' => static::CACHE_TIME,
        ],
      ];
    } catch (\Exception $ex) {
      return [
        '#markup' => $translation_manager
          ->translate('Could not read @url', [
          '@url' => $url,
        ]),
      ];
    }
    return [
      '#markup' => 'here',
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DashboardBase::$cache protected property Cache backend.
DashboardBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 8
DashboardBase::getCache protected function Get cache for cid.
DashboardBase::massageFormValues public function Validate settings form.
DashboardBase::setCache protected function Set a new cache entry. Cache is prefixed by pluginid.
DashboardBase::validateForm public function Validate settings form. 1
DashboardBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct 8
DashboardLazyBuildBase::buildRenderArray public function Build render array. Overrides DashboardBase::buildRenderArray
DashboardLazyBuildBase::lazyBuildPreRender public static function Helper for lazy build render. Overrides DashboardLazyBuildInterface::lazyBuildPreRender
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
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::isConfigurable public function Determines if the plugin is configurable.
RssNews::buildSettingsForm public function Build render array. Overrides DashboardBase::buildSettingsForm
RssNews::CACHE_TIME constant Default cache time.
RssNews::lazyBuild public static function Lazy builder callback. Overrides DashboardLazyBuildInterface::lazyBuild
RssNews::readSource public static function Fetch rss items.
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.