<?php

declare(strict_types=1);

namespace apexl\Io\services;

use Stash\Pool;

class Cache extends Pool
{
    /**
     * Trys to get an item from the cache, if it doesn't exist it will be created using the callback.
     */
    public function remember(string $key, callable $callback, int $ttl = null): mixed
    {
        $item = $this->getItem($key);

        $data = $item->get();

        if ($item->isMiss()) {
            $item->lock();
            $data = $callback();

            if ($ttl !== null) {
                $item->expiresAfter($ttl);
            }

            $this->save($item->set($data));
        }

        return $data;
    }
}
