<?php

namespace App\Twig\Extension;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

/**
 * class LazyLoadExtension.
 *
 * @author Simon Vieille <simon@deblan.fr>
 */
class LazyLoadExtension extends AbstractExtension
{
    public function getFilters()
    {
        return [
            new TwigFilter('lazy_load', [$this, 'lazyLoad'], ['is_safe' => ['html']]),
        ];
    }

    public function lazyLoad($text)
    {
        $text = preg_replace_callback(
            '`<img src="([^"]+)" alt="([^"]+)" />`isU',
            function ($data) {
                $lazy = sprintf('<img class="lazy-img" src="#" data-src="%s" alt="%s" />', $data[1], $data[2]);
                $noScript = sprintf('<noscript>%s</noscript>', $data[0]);

                return $lazy.$noScript;
            },
            $text
        );

        return $text;
    }
}
