<?php


namespace App\Twig;


use Kadet\Highlighter\Formatter\HtmlFormatter;
use Kadet\Highlighter\KeyLighter;
use Kadet\Highlighter\Language\Language;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use function Kadet\Highlighter\highlight;

class KeyLighterExtension extends AbstractExtension
{
    private $formatter;

    public function getFilters()
    {
        return [
            new TwigFilter('highlight', function($source, $language) {
                if (!$language instanceof Language) {
                    $language = KeyLighter::get()->getLanguage($language);
                }

                return highlight($source, $language, $this->getFormatter());
            }, ['pre_escape' => 'html', 'is_safe' => ['html']])
        ];
    }

    public function getFormatter()
    {
        return $this->formatter ?: $this->formatter = new HtmlFormatter();
    }
}
