progressive_image_loading-8.x-1.x-dev/src/Plugin/Filter/RevertProgressiveImageLoadingFilter.php
src/Plugin/Filter/RevertProgressiveImageLoadingFilter.php
<?php
namespace Drupal\progressive_image_loading\Plugin\Filter;
use Drupal\Component\Utility\Html as HtmlUtility;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
/**
* Provides a filter to revert the progressive image loading changes.
*
* @Filter(
* id = "progressive_image_loading_revert",
* title = @Translation("Revert Progressive Image Loading changes"),
* type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE
* )
*/
class RevertProgressiveImageLoadingFilter extends FilterBase {
/**
* {@inheritdoc}
*/
public function process($text, $langcode) {
$result = new FilterProcessResult($text);
$dom = HtmlUtility::load($text);
$xpath = new \DOMXPath($dom);
$images = $xpath->query('//img');
if ($images->length) {
/** @var \DOMElement[] $images */
foreach ($images as $image) {
if ($image->hasAttribute('data-srcset')) {
$image->setAttribute('srcset', $image->getAttribute('data-srcset'));
$image->removeAttribute('data-srcset');
}
elseif ($image->hasAttribute('data-src')) {
$image->setAttribute('src', $image->getAttribute('data-src'));
$image->removeAttribute('data-src');
}
}
}
$backgrounds = $xpath->query('//*[@data-background-image]');
if ($backgrounds->length) {
/** @var \DOMElement[] $backgrounds */
foreach ($backgrounds as $background) {
$url = $background->getAttribute('data-background-image');
$style = 'background-image: url("' . $url . '")' . $background->getAttribute('style');
$background->setAttribute('style', $style);
foreach ($background->attributes as $name => $attribute) {
if (strpos($name, 'data-background-image') !== FALSE) {
$background->removeAttribute($name);
}
}
}
}
$iframes = $xpath->query('//iframe');
if ($iframes->length) {
/** @var \DOMElement[] $iframes */
foreach ($iframes as $iframe) {
if ($iframe->hasAttribute('data-src')) {
$iframe->setAttribute('src', $image->getAttribute('data-src'));
$iframe->removeAttribute('data-src');
}
}
}
if ($images->length || $backgrounds->length || $iframes->length) {
$result->setProcessedText(HtmlUtility::serialize($dom));
}
return $result;
}
}
