<?php

namespace CouponsPlus\App\Coupon\Tree\Factories;

use CouponsPlus\App\Conditions\Abilities\TestableComposite;
use CouponsPlus\App\Coupon\Tree\Abilities\TestableGroupData;

class CachedTestableGroupFactoryFromData implements TestableGroupFactoryFromDataInterface
{
    private array $cache = [];
    private TestableGroupFactoryFromDataInterface $decoratedFactory;

    public function __construct(TestableGroupFactoryFromDataInterface $decoratedFactory)
    {
        $this->decoratedFactory = $decoratedFactory;
    }

    public function create($testableGroupData): TestableComposite
    {
        $cacheKey = spl_object_hash($testableGroupData);

        if (isset($this->cache[$cacheKey])) {
            return $this->cache[$cacheKey];
        }

        $result = $this->decoratedFactory->create($testableGroupData);

        $this->cache[$cacheKey] = $result;

        return $result;
    }
}
