<?php

namespace RTMCustomMails;

use Throwable;
use Timber\Loader;
use Twig\Source;
use WordpressModels\Traits\SingletonTrait;

/**
 *
 */
class Twig
{

    use SingletonTrait;

    public function __construct()
    {
        add_filter('acf/validate_value/name=text', [$this, 'validateTwigTemplate'], 10, 4);
    }

    /**
     * @param $valid
     * @param $value
     * @param $field
     * @param $input
     * @return bool|string
     */
    public function validateTwigTemplate($valid, $value, $field, $input): bool|string
    {
        if ($value && is_string($value)) {
            try {
                // try to tokenize the template, throws exception if tempalte is invalid
                (new Loader())->get_twig()->tokenize(new Source(wp_unslash($value), $input));
            } catch (Throwable $exception) {
                // return custom error message
                return "Invalid Template: " . $exception->getMessage();
            }
        }

        // no exception thrown, template is valid
        return true;
    }
}