<?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 GlobalConstantType extends CodeDiscoveryDependentType
{
    /** @var StructuralElementDeclarations */
    private $elementsRegistry;
    /** @var string  */
    private $constantName;

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

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

        $types = [];
        foreach ($this->elementsRegistry->findGlobalConstant($this->constantName) as $c) {
            $types[] = $c->getType();
        }
        $types = array_values(array_unique($types));

        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);
        }
    }
}
