<?php

declare (strict_types=1);
namespace PoP\ComponentModel\Cache;

use PoP\ComponentModel\Module;
use PoP\ComponentModel\ModuleInfo;
use PoP\ComponentModel\Constants\CachePlaceholders;
use PoP\Root\App;
/** @internal */
trait ReplaceCurrentExecutionDataWithPlaceholdersTrait
{
    /**
     * @return array<string,string>
     */
    protected function getCacheReplacements() : array
    {
        /** @var ModuleInfo */
        $moduleInfo = App::getModule(Module::class)->getInfo();
        // @phpstan-ignore-next-line
        return [$moduleInfo->getUniqueID() => CachePlaceholders::UNIQUE_ID, (string) $moduleInfo->getRand() => CachePlaceholders::RAND, (string) $moduleInfo->getTime() => CachePlaceholders::TIME];
    }
    protected function replaceCurrentExecutionDataWithPlaceholders(string $content) : string
    {
        $replacements = $this->getCacheReplacements();
        return \str_replace(\array_keys($replacements), \array_values($replacements), $content);
    }
    /**
     * @param string|string[]|null $content
     * @return string|string[]|null
     */
    protected function replacePlaceholdersWithCurrentExecutionData(string|array|null $content) : string|array|null
    {
        /**
         * Content may be null if it had not been cached
         */
        if ($content === null) {
            return null;
        }
        // Replace the placeholder for the uniqueId with the current uniqueId
        // Do the same with all dynamic constants, so that we can generate a proper ETag also when retrieving the cached value
        $replacements = $this->getCacheReplacements();
        $replaceFrom = \array_values($replacements);
        $replaceTo = \array_keys($replacements);
        if (\is_array($content)) {
            /**
             * A faster way to replace the strings in multidimensional array
             * is to json_encode() it, do the str_replace() and then json_decode() it
             * @see https://www.php.net/manual/en/function.str-replace.php#100871
             */
            return \json_decode(\str_replace($replaceFrom, $replaceTo, (string) \json_encode($content)), \true);
        }
        return \str_replace($replaceFrom, $replaceTo, $content);
    }
}
