<?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\Reflection\Type;

use Magento\Mray\CodeStructuralElement\Php\Reflection\Context\StructuralElementDeclarations;
use Magento\Mray\CodeStructuralElement\Php\Reflection\TypeFactory;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types;
use function array_unique;
use function array_values;
use function count;

class FunctionReturnType extends CodeDiscoveryDependentType
{
    /** @var StructuralElementDeclarations  */
    private $elementsRegistry;
    /** @var string  */
    private $fnName;

    /**
     * @param StructuralElementDeclarations $elementsRegistry
     * @param string $fnName
     */
    public function __construct(
        StructuralElementDeclarations $elementsRegistry,
        string $fnName
    ) {
        $this->elementsRegistry = $elementsRegistry;
        $this->fnName = $fnName;
    }

    /**
     * @return Type
     */
    public function getEstimatedType(): Type
    {
        if ($this->cycle()) {
            return $this->estimated = TypeFactory::get(Types\Mixed_::class);
        }

        $types = [];
        foreach ($this->elementsRegistry->findFunction($this->fnName) as $fn) {
            $types[] = $fn->getReturnType();
        }
        $types = array_values(array_unique($types)); // invokes to string inside
        switch (count($types)) {
            case 1:
                return $this->estimated = $types[0];
            case 0:
                return $this->estimated = TypeFactory::get(Types\Mixed_::class);
            default:
                return $this->estimated = TypeFactory::get(Types\Compound::class, $types);
        }
    }
}
