<?php
/**
 * Copyright 2020 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it.
 */
declare(strict_types=1);

namespace Magento\Mray\CodeStructuralElement\Php\NodeRuntimeTypeResolver;

use Magento\Mray\CodeStructuralElement\Php\Reflection;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types;
use PhpParser\Node\Expr;
use function array_map;
use function get_class;

class Composite implements Resolver, Contextual
{
    use Context;

    /**
     * @var Resolver[]
     */
    private $resolversMap;

    /**
     * @param Resolver[] $resolversMap
     */
    public function __construct(array $resolversMap)
    {
        $this->resolversMap = array_map(function (Resolver $resolver) {
            return $resolver;
        }, $resolversMap);
    }

    /**
     * @param Expr $expr
     * @return Type
     */
    public function resolve(Expr $expr): Type
    {
        $exprType = get_class($expr);
        if (!isset($this->resolversMap[$exprType])) {
            return Reflection\TypeFactory::get(Types\Mixed_::class);
        }

        return $this->resolversMap[$exprType]->resolve($expr);
    }

    /**
     * @param Reflection\Context $context
     */
    public function setContext(Reflection\Context $context): void
    {
        foreach ($this->resolversMap as $resolver) {
            if ($resolver instanceof Contextual) {
                $resolver->setContext($context);
            }
        }
        $this->context = $context;
    }
}
