You are here

class InsertView in Insert View 2.0.x

Same name and namespace in other branches
  1. 8 src/Plugin/Filter/InsertView.php \Drupal\insert_view\Plugin\Filter\InsertView

Provides a filter for insert view.

Plugin annotation


@Filter(
  id = "insert_view",
  module = "insert_view",
  title = @Translation("Insert View"),
  description = @Translation("Allows to embed views using the simple syntax: [view:name=display=args=limit:number]"),
  type = Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE,
)

Hierarchy

Expanded class hierarchy of InsertView

File

src/Plugin/Filter/InsertView.php, line 21

Namespace

Drupal\insert_view\Plugin\Filter
View source
class InsertView extends FilterBase implements TrustedCallbackInterface {

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
    $result = new FilterProcessResult($text);
    if (!empty($text)) {
      $match = [];
      if (preg_match_all("/\\[view:([^=\\]]+)=?([^=\\]]+)?=?([^=\\]]+)?=?(?:limit:)?([\\d]+)?\\]/i", $text, $match)) {
        $search = $replace = [];
        foreach ($match[0] as $key => $value) {
          $view_name = $match[1][$key];
          $display_id = $match[2][$key] && !is_numeric($match[2][$key]) ? $match[2][$key] : 'default';
          $args = $match[3][$key];
          $limit = $match[4][$key] ?? '';

          // Let's create a placeholder from the renderable array of the view.
          $view_output = $result
            ->createPlaceholder('\\Drupal\\insert_view\\Plugin\\Filter\\InsertView::build', [
            $view_name,
            $display_id,
            $args,
            $limit,
          ]);

          // Populate the replace statement.
          $search[] = $value;
          $replace[] = !empty($view_output) ? $view_output : '';
        }
        $text = str_replace($search, $replace, $text);

        // Add some more caching options.
        $result
          ->setProcessedText($text)
          ->addCacheTags([
          'insert_view',
        ])
          ->addCacheContexts([
          'url',
          'user.permissions',
        ]);
      }
    }
    return $result;
  }

  /**
   * The parameters to tag syntax.
   *
   * @param mixed $view_name
   *   The name of the view.
   * @param mixed $display_id
   *   The display ID of the view.
   * @param mixed $args
   *   An associative array of arguments.
   * @param string $limit
   *   The limit to itens per page.
   *
   * @return array
   *   A renderable array containing the view output
   */
  public static function build($view_name, $display_id, $args, $limit = '') {
    $plain = '';
    $view = Views::getView($view_name);
    if (empty($view)) {

      // Return renderable array.
      return [
        '#attached' => [],
        '#markup' => $plain,
      ];
    }
    if (!$view
      ->access($display_id)) {

      // Return renderable array.
      return [
        '#attached' => [],
        '#markup' => $plain,
      ];
    }
    $current_path = \Drupal::service('path.current')
      ->getPath();
    $url_args = explode('/', $current_path);
    foreach ($url_args as $id => $arg) {
      $args = str_replace("%{$id}", $arg, $args);
    }
    $args = preg_replace(',/?(%\\d),', '', $args);
    $args = $args ? explode('/', $args) : [];
    if (is_numeric($limit)) {
      $view
        ->setItemsPerPage($limit);
    }
    return $view
      ->preview($display_id, $args);
  }

  /**
   * {@inheritdoc}
   */
  public function tips($long = FALSE) {
    if ($long) {
      $output = '<br />';
      $output .= '<dl>';
      $output .= '<dt>' . $this
        ->t('Insert view filter allows to embed views using tags. The tag syntax is relatively simple: [view:name=display=args=limit:number]') . '</dt>';
      $output .= '<dt>' . $this
        ->t('For example [view:tracker=page=1] says, embed a view named "tracker", use the "page" display, and supply the argument "1".') . '</dt>';
      $output .= '<dt>' . $this
        ->t("The <em>display</em>, <em>args</em>, and <em>limit</em> parameters can be omitted. If the display is left empty, the view\\'s default display is used. If the limit is left empty, the view display\\'s settings are used. Use <em>0</em> to show all results.") . '</dt>';
      $output .= '<dt>' . $this
        ->t('Multiple arguments are separated with slash. The <em>args</em> format is the same as used in the URL (or view preview screen).') . '</dt>';
      $output .= '</dl>';
      $output .= $this
        ->t('Valid examples:');
      $output .= '<dl>';
      $output .= '<dt>[view:my_view]</dt>';
      $output .= '<dt>[view:my_view=my_display]</dt>';
      $output .= '<dt>[view:my_view=my_display=arg1/arg2/arg3=limit:number]</dt>';
      $output .= '<dt>[view:my_view==arg1/arg2/arg3]</dt>';
      $output .= '<dt>[view:my_view===limit:0]</dt>';
      $output .= '</dl>';
      $output .= '<br />';
      return $output;
    }
    else {
      return $this
        ->t('You may use [view:<em>name=display=args</em>] tags to display views.');
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function trustedCallbacks() {
    return [
      'build',
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FilterBase::$provider public property The name of the provider that owns this filter.
FilterBase::$settings public property An associative array containing the configured settings of this filter.
FilterBase::$status public property A Boolean indicating whether this filter is enabled.
FilterBase::$weight public property The weight of this filter compared to others in a filter collection.
FilterBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 1
FilterBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration
FilterBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
FilterBase::getDescription public function Returns the administrative description for this filter plugin. Overrides FilterInterface::getDescription
FilterBase::getHTMLRestrictions public function Returns HTML allowed by this filter's configuration. Overrides FilterInterface::getHTMLRestrictions 4
FilterBase::getLabel public function Returns the administrative label for this filter plugin. Overrides FilterInterface::getLabel
FilterBase::getType public function Returns the processing type of this filter plugin. Overrides FilterInterface::getType
FilterBase::prepare public function Prepares the text for processing. Overrides FilterInterface::prepare
FilterBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration 1
FilterBase::settingsForm public function Generates a filter's settings form. Overrides FilterInterface::settingsForm 3
FilterBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct 4
FilterInterface::TYPE_HTML_RESTRICTOR constant HTML tag and attribute restricting filters to prevent XSS attacks.
FilterInterface::TYPE_MARKUP_LANGUAGE constant Non-HTML markup language filters that generate HTML.
FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE constant Irreversible transformation filters.
FilterInterface::TYPE_TRANSFORM_REVERSIBLE constant Reversible transformation filters.
InsertView::build public static function The parameters to tag syntax.
InsertView::process public function Performs the filter processing. Overrides FilterInterface::process
InsertView::tips public function Generates a filter's tip. Overrides FilterBase::tips
InsertView::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
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 2
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.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
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.