<?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\TypeFactory;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types;
use PhpParser\Node\Expr;
use function array_unique;
use function array_values;
use function count;

class CoalesceOperators implements Resolver
{
    /** @var Memorized  */
    private $memorized;

    /**
     * CoalesceOperators constructor.
     */
    public function __construct()
    {
        $this->memorized = new Memorized();
    }

    /**
     * @param Expr $expr
     * @return Type
     */
    public function resolve(Expr $expr): Type
    {
        $operandTypes = [];
        foreach ($expr->getSubNodeNames() as $operand) {
            $operandType = $this->memorized->resolve($expr->{$operand});
            if ($operandType instanceof Types\Mixed_) {
                return $operandType;
            }
            $operandTypes[] = $operandType;
        }
        $operandTypes = array_values(array_unique($operandTypes));
        if (count($operandTypes) === 1) {
            return $operandTypes[0];
        }

        return TypeFactory::get(Types\Compound::class, $operandTypes);
    }
}
