You are here

public function InlineResponsiveImage::process in Inline responsive images 7

Same name and namespace in other branches
  1. 8 src/Plugin/Filter/InlineResponsiveImage.php \Drupal\inline_responsive_image\Plugin\Filter\InlineResponsiveImage::process()

File

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

Class

InlineResponsiveImage
Plugin annotation @Filter( id = "inline_responsive_image", title = @Translation("Inline responsive images"), description = @Translation("Filter for inline responsive images"), type =…

Namespace

Drupal\inline_responsive_image\Plugin\Filter

Code

public function process($text, $langcode) {
  $result = new FilterProcessResult($text);
  if (stristr($text, 'data-style') !== FALSE) {
    $dom = Html::load($text);
    $xpath = new \DOMXPath($dom);
    foreach ($xpath
      ->query('//*[@data-style]') as $node) {
      $style = $node
        ->getAttribute('data-style');
      $caption = $node
        ->getAttribute('data-caption');
      $align = $node
        ->getAttribute('data-align');
      $entityUuid = $node
        ->getAttribute('data-entity-uuid');
      $responsive = ResponsiveImageStyle::load($style) ? true : false;
      $file = \Drupal::entityManager()
        ->loadEntityByUuid('file', $entityUuid);
      if ($file) {
        if ($responsive) {
          $responsiveImage = array(
            '#theme' => 'inline_responsive_image',
            '#image' => array(
              '#type' => 'responsive_image',
              '#responsive_image_style_id' => $style,
              '#uri' => $file
                ->getFileUri(),
            ),
            '#attributes' => array(
              'class' => array(),
            ),
            '#caption' => !empty($caption) ? $caption : '',
          );
        }
        else {
          $image_style = ImageStyle::load($style);
          $responsiveImage = array(
            '#theme' => 'inline_responsive_image',
            '#image' => array(
              '#type' => 'image_formatter',
              '#style_name' => $style,
              '#url' => $file
                ->getFileUri(),
            ),
            '#attributes' => array(
              'class' => array(
                'test' => 'test',
              ),
            ),
            '#caption' => !empty($caption) ? $caption : '',
          );
        }
        $responsiveImage['#attributes']['class'][] = $style;
        if (!empty($align)) {
          $responsiveImage['#attributes']['class'][] = $align;
        }
        $responsiveImageHtml = \Drupal::service('renderer')
          ->render($responsiveImage);
        $fragment = $dom
          ->createDocumentFragment();
        if ($fragment
          ->appendXML($responsiveImageHtml)) {
          $node->parentNode
            ->replaceChild($fragment, $node);
        }
      }
    }
    $result
      ->setProcessedText(Html::serialize($dom));
  }
  return $result;
}