public function LazyFilter::process in Lazy-load 8
Same name and namespace in other branches
- 8.3 src/Plugin/Filter/LazyFilter.php \Drupal\lazy\Plugin\Filter\LazyFilter::process()
- 8.2 src/Plugin/Filter/LazyFilter.php \Drupal\lazy\Plugin\Filter\LazyFilter::process()
Performs the filter processing.
Parameters
string $text: The text string to be filtered.
string $langcode: The language code of the text to be filtered.
Return value
\Drupal\filter\FilterProcessResult The filtered text, wrapped in a FilterProcessResult object, and possibly with associated assets, cacheability metadata and placeholders.
Overrides FilterInterface::process
See also
\Drupal\filter\FilterProcessResult
File
- src/
Plugin/ Filter/ LazyFilter.php, line 25
Class
- LazyFilter
- Provides a filter to lazy-load images.
Namespace
Drupal\lazy\Plugin\FilterCode
public function process($text, $langcode) {
$config = \Drupal::config('lazy.settings')
->get();
$opt_skipClass = $config['skipClass'];
$opt_selector = ltrim($config['selector'], '.');
$opt_tags = $config['alter_tag'];
$opt_src = $config['src'] !== 'src' ? $config['src'] : 'data-filterlazy-src';
$opt_placeholderSrc = $config['placeholderSrc'];
$result = new FilterProcessResult($text);
$html_dom = Html::load($text);
$pages = $config['disabled_paths'];
$path_matches = lazy_disabled_by_path($pages);
if (!$path_matches) {
foreach ($opt_tags as $tag => $status) {
$matches = $html_dom
->getElementsByTagName($tag);
foreach ($matches as $element) {
$classes = $element
->getAttribute('class');
$classes = strlen($classes) > 0 ? explode(' ', $classes) : [];
$parent_classes = $element->parentNode
->getAttribute('class');
$parent_classes = strlen($parent_classes) > 0 ? explode(' ', $parent_classes) : [];
if (empty($opt_tags[$tag])) {
// If the `tag` is not enabled remove the bLazy selector class.
if (($key = array_search($opt_selector, $classes, FALSE)) !== FALSE) {
unset($classes[$key]);
$element
->setAttribute('class', implode(' ', $classes));
if (empty($classes)) {
$element
->removeAttribute('class');
}
}
}
else {
// `tag` is enabled. Make sure skipClass is not set before proceeding.
if (!in_array($opt_skipClass, $classes, FALSE) && !in_array($opt_skipClass, $parent_classes, FALSE)) {
$classes[] = $opt_selector;
$classes = array_unique($classes);
$element
->setAttribute('class', implode(' ', $classes));
$src = $element
->getAttribute('src');
$element
->removeAttribute('src');
$element
->setAttribute($opt_src, $src);
$element
->setAttribute('src', $opt_placeholderSrc);
}
}
}
}
}
$result
->setProcessedText(Html::serialize($html_dom));
return $result;
}