<?php


namespace AutoAdmin\Bundle\Core\Twig;


use AutoAdmin\Bundle\Core\Helper\CacheSuffixHelper;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

class UtilExtension extends AbstractExtension
{
    private CacheSuffixHelper $cacheSuffixHelper;

    public function __construct(CacheSuffixHelper $cacheSuffixHelper)
    {
        $this->cacheSuffixHelper = $cacheSuffixHelper;
    }

    /**
     * Returns the Twig functions of this extension.
     *
     * @return TwigFunction[]
     */
    public function getFunctions(): array
    {
        return [
            new TwigFunction('twig_function_exists', [$this, 'twigFunctionExists'], ['needs_environment' => true]),
            new TwigFunction('aa_get_cache_suffix', [$this, 'getCacheSuffix']),
        ];
    }

    public function getFilters(): array
    {
        return [
            new TwigFilter('aa_add_cache_suffix', [$this, 'addCacheSuffix']),
        ];
    }

    public function twigFunctionExists(Environment $twig, string $functionName): bool
    {
        $function = $twig->getFunction($functionName);

        return $function !== false && $function !== null;
    }

    public function addCacheSuffix($input): string
    {
        if (!is_string($input) || false === ($cacheSuffix = $this->cacheSuffixHelper->getCacheSuffix())) {
            return $input;
        }

        $link = stripos($input, '?') === false ? '?' : '&';

        return $input . $link . 'cs=' . $cacheSuffix;
    }

    public function getCacheSuffix(): string
    {
        return $this->cacheSuffixHelper->getCacheSuffix();
    }
}
