<?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\VariableDefinition;

use Magento\Mray\CodeStructuralElement\Php\Reflection\TypeFactory;
use Magento\Mray\CodeStructuralElement\Php\Reflection\ValueAccessor;
use Magento\Mray\CodeStructuralElement\Php\Reflection\VariableDefinition;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types;
use PhpParser\Node;

class Param implements VariableDefinition
{
    /** @var Node\Param  */
    private $node;
    /** @var ValueAccessor|ValueAccessor\Expr  */
    private $accessor;

    /**
     * @param Node\Param $node
     */
    public function __construct(Node\Param $node)
    {
        $this->node = $node;
        $this->accessor = new ValueAccessor\Expr($node->var);
    }

    /**
     * @return bool
     */
    public function isDefinition(): bool
    {
        return true;
    }

    /**
     * @return ValueAccessor
     */
    public function getAccessor(): ValueAccessor
    {
        return $this->accessor;
    }

    /**
     * @return Type
     */
    public function getType(): Type
    {
        $type = $this->getExpectedArgumentType();
        if ($this->isVariadic()) {
            $type = TypeFactory::get(Types\Array_::class, $type);
        }
        return $type;
    }

    /**
     * @return Type
     */
    private function getExpectedArgumentType(): Type
    {
        return TypeFactory::cast($this->node->type);
    }

    /**
     * @return bool
     */
    private function isVariadic(): bool
    {
        return $this->node->variadic;
    }
}
