<?php
/*
 * Copyright © ProgramCMS. All rights reserved.
 * See COPYING.txt for license details.
 *
 * Developed by Mohamed EL QUCHIRI <elquchiri@gmail.com>
 */

namespace ProgramCms\CoreBundle\App\Config;

use ProgramCms\CoreBundle\App\ScopeResolverPool;
use ProgramCms\CoreBundle\App\ScopeConfigInterface;
use ProgramCms\CoreBundle\App\ScopeInterface;

/**
 * Class ScopeCodeResolver
 * @package ProgramCms\CoreBundle\App\Config
 */
class ScopeCodeResolver
{
    /**
     * @var ScopeResolverPool
     */
    private $scopeResolverPool;

    /**
     * @var array
     */
    private $resolvedScopeCodes = [];

    /**
     * @param ScopeResolverPool $scopeResolverPool
     */
    public function __construct(ScopeResolverPool $scopeResolverPool)
    {
        $this->scopeResolverPool = $scopeResolverPool;
    }

    /**
     * Resolve scope code
     *
     * @param string $scopeType
     * @param string|null $scopeCode
     * @return string
     */
    public function resolve($scopeType, $scopeCode)
    {
        if (isset($this->resolvedScopeCodes[$scopeType][$scopeCode])) {
            return $this->resolvedScopeCodes[$scopeType][$scopeCode];
        }

        if ($scopeType !== ScopeConfigInterface::SCOPE_TYPE_DEFAULT) {
            $scopeResolver = $this->scopeResolverPool->get($scopeType);
            $resolverScopeCode = $scopeResolver->getScope($scopeCode);
        } else {
            $resolverScopeCode = $scopeCode;
        }

        if ($resolverScopeCode instanceof ScopeInterface) {
            $resolverScopeCode = $resolverScopeCode->getCode();
        }

        if ($scopeCode === null) {
            $scopeCode = $resolverScopeCode;
        }

        $this->resolvedScopeCodes[$scopeType][$scopeCode] = $resolverScopeCode;

        return $resolverScopeCode;
    }
}