You are here

class FilterResponsiveWrappers in Responsive wrappers 8

Same name and namespace in other branches
  1. 2.0.x src/Plugin/Filter/FilterResponsiveWrappers.php \Drupal\responsivewrappers\Plugin\Filter\FilterResponsiveWrappers

Check the content and add responsive classes and wrappers.

Plugin annotation


@Filter(
  id = "filter_bootstrap_responsive_wrapper",
  title = @Translation("Responsive wrappers filter"),
  description = @Translation("Scans content to add responsive wrappers and classes to make it responsive."),
  type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE
)

Hierarchy

Expanded class hierarchy of FilterResponsiveWrappers

File

src/Plugin/Filter/FilterResponsiveWrappers.php, line 20

Namespace

Drupal\responsivewrappers\Plugin\Filter
View source
class FilterResponsiveWrappers extends FilterBase {

  /**
   * Implements filter processor.
   */
  public function process($text, $langcode) {
    $result = new FilterProcessResult($text);
    if ($this->settings['responsive_iframe'] || $this->settings['responsive_table'] || $this->settings['responsive_image']) {

      // Module base config.
      $config = \Drupal::config('responsivewrappers.settings');
      $dom = Html::load($text);

      // Responsive video wrapper.
      if ($this->settings['responsive_iframe']) {
        $iframes = $dom
          ->getElementsByTagName('iframe');
        $video_pattern = $this->settings['responsive_iframe_pattern'];
        foreach ($iframes as $iframe) {

          // Video detection pattern.
          $iframe_src = $iframe
            ->getAttribute('src');
          if (preg_match($video_pattern, $iframe_src)) {

            // Video wrapper.
            $video_wrapper_class = $iframe->parentNode->tagName === 'div' ? $iframe->parentNode
              ->getAttribute('class') : '';

            // If exists, replace video-embed-field functionality.
            if (strpos($video_wrapper_class, 'video-embed-field-responsive-video') !== FALSE) {
              $video_wrapper_class = str_replace('video-embed-field-responsive-video', 'embed-responsive embed-responsive-16by9', $video_wrapper_class);
              $iframe->parentNode
                ->setAttribute('class', $video_wrapper_class);
            }
            elseif (strpos($video_wrapper_class, 'embed-responsive') === FALSE) {

              // If not exists create the wrapper.
              $video_wrapper = $dom
                ->createElement('div');
              $video_wrapper
                ->setAttribute('class', 'embed-responsive embed-responsive-16by9');
              $iframe = $iframe->parentNode
                ->replaceChild($video_wrapper, $iframe);
              $video_wrapper
                ->appendChild($iframe);
            }

            // Video class.
            $video_class = $iframe
              ->getAttribute('class');
            if (empty($video_class) || !in_array('embed-responsive-item', explode(' ', $video_class))) {
              $iframe
                ->setAttribute('class', trim($video_class . ' embed-responsive-item'));
            }
          }
        }
      }

      // Responsive table wrapper and class.
      if ($this->settings['responsive_table']) {
        $tables = $dom
          ->getElementsByTagName('table');
        foreach ($tables as $table) {

          // Table wrapper.
          $table_wrapper_class = $table->parentNode->tagName === 'div' ? $table->parentNode
            ->getAttribute('class') : '';
          if (strpos($table_wrapper_class, 'table-responsive') === FALSE) {
            $table_wrapper = $dom
              ->createElement('div');
            $table_wrapper
              ->setAttribute('class', 'table-responsive');
            $table = $table->parentNode
              ->replaceChild($table_wrapper, $table);
            $table_wrapper
              ->appendChild($table);
          }

          // Table class.
          $table_class = $table
            ->getAttribute('class');
          if (empty($table_class) || !in_array('table', explode(' ', $table_class))) {
            $table
              ->setAttribute('class', trim($table_class . ' table'));
          }
        }
      }

      // Responsive image class.
      if ($this->settings['responsive_image']) {
        $images = $dom
          ->getElementsByTagName('img');
        foreach ($images as $image) {

          // Image class.
          $image_class = $image
            ->getAttribute('class');
          $responsive_class = 4 === $config
            ->get('version') ? 'img-fluid' : 'img-responsive';
          if (strpos($image_class, $responsive_class) === FALSE) {
            $image
              ->setAttribute('class', trim($image_class . ' ' . $responsive_class));
          }
        }
      }
      $result
        ->setProcessedText(Html::serialize($dom));

      // Attach responsive CSS if needed.
      if ($config
        ->get('add_css')) {
        if (4 === $config
          ->get('version')) {
          $result
            ->setAttachments([
            'library' => [
              'responsivewrappers/responsivewrappers_v4',
            ],
          ]);
        }
        else {
          $result
            ->setAttachments([
            'library' => [
              'responsivewrappers/responsivewrappers_v3',
            ],
          ]);
        }
      }
    }
    return $result;
  }

  /**
   * Implements settings filter form.
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form['responsive_iframe'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Responsive video'),
      '#default_value' => isset($this->settings['responsive_iframe']) ? $this->settings['responsive_iframe'] : '',
      '#description' => $this
        ->t('Add responsive wrapper for videos (16/9 aspect ratio).'),
    ];
    $form['responsive_iframe_pattern'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Source video pattern detection'),
      '#default_value' => isset($this->settings['responsive_iframe_pattern']) ? $this->settings['responsive_iframe_pattern'] : '#.*(youtube.|vimeo.).*#ui',
      '#description' => $this
        ->t('Regular expresion for source video detection. This pattern evaluates scr iframe attribute.'),
    ];
    $form['responsive_table'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Responsive tables'),
      '#default_value' => isset($this->settings['responsive_table']) ? $this->settings['responsive_table'] : '',
      '#description' => $this
        ->t('Add responsive wrapper for tables.'),
    ];
    $form['responsive_image'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Responsive images'),
      '#default_value' => isset($this->settings['responsive_image']) ? $this->settings['responsive_image'] : '',
      '#description' => $this
        ->t('Add responsive class for images.'),
    ];
    return $form;
  }

}

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
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::tips public function Generates a filter's tip. Overrides FilterInterface::tips 9
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.
FilterResponsiveWrappers::process public function Implements filter processor. Overrides FilterInterface::process
FilterResponsiveWrappers::settingsForm public function Implements settings filter form. Overrides FilterBase::settingsForm
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::$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.
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.