<?php

namespace Drupal\pagedesigner;

use Drupal\Core\Template\TwigEnvironment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

/**
 * Extend Drupal's Twig_Extension class.
 */
class CustomFunctionTwigExtension extends AbstractExtension {

  /**
   * Constructs a CustomFunctionTwigExtension.
   *
   * @param \Drupal\Core\Template\TwigEnvironment $twig
   *   The twig service.
   */
  public function __construct(protected TwigEnvironment $twig) {
  }

  /**
   * {@inheritdoc}
   */
  public function getFunctions() {
    return [
      new TwigFunction('custom_function', [$this, 'callFunction']),
    ];
  }

  /**
   * Returns associative array from $string.
   *
   * @param string $function
   *   Funciton to be called.
   * @param string $args
   *   Arguments.
   */
  public function callFunction($function, ...$args) {
    $fn = $this->twig->getFunction($function);

    if ($fn === FALSE) {
      return NULL;
    }

    return $fn->getCallable()(...$args);
  }

}
