<?php
namespace Helpers\Outil;

use Psr\SimpleCache\CacheInterface;

trait MemoizeTrait
{
    

    /**
     * @source https://github.com/ihor/Nspl?tab=readme-ov-file#memoizedfunction
     * @example
     * $memoized = memoized($f);
     * echo $memoized('Hello world!');
     * echo $memoized('Hello world!');
     *
     * @param array<mixed> $args
     * @return mixed
     */
    protected function memoize(string $funcName, array $args, callable $function)
    {
        $cache = self::getCache();
        $key = $funcName . serialize($args);
        if (! $cache->has($key)) {
            $cache->set($key, call_user_func_array($function, $args));
        }

        return $cache->get($key);
    }

    protected function memoizeClear() :void
    {
        self::getCache()->clear();
    }

//_____________________________________________________________________________

    private static ?CacheInterface $CACHE = null;
    
    private static function getCache() :CacheInterface
    {
        if (self::$CACHE === null) {
            self::$CACHE = new LightCache();
        }
        return self::$CACHE;
    }
}
