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

use Magento\Mray\CodeStructuralElement\Php\Reflection\Context;
use Magento\Mray\CodeStructuralElement\Php\Reflection;

class Global_ implements Context
{
    use VariableScope;

    /** @var string[] */
    private $superGlobals = [];
    /** @var StructuralElementDeclarations */
    private $structuralElementDeclarations;

    /**
     * @param StructuralElementDeclarations|null $structuralElementDeclarations
     */
    public function __construct(?StructuralElementDeclarations $structuralElementDeclarations = null)
    {
        $this->structuralElementDeclarations = $structuralElementDeclarations ?? new StructuralElementDeclarations();
    }

    /**
     * @return StructuralElementDeclarations
     */
    public function getStructuralElementDeclarations(): StructuralElementDeclarations
    {
        return $this->structuralElementDeclarations;
    }

    /**
     * @param string $name
     * @return Reflection\Variable
     */
    public function getVariable(string $name): Reflection\Variable
    {
        if (!isset($this->variables[$name])) {
            $this->variables[$name] = new Reflection\Variable(
                new Reflection\VariableDefinition\Unknown($name)
            );
        }
        return $this->variables[$name];
    }

    /**
     * @return Global_
     */
    public function getGlobal(): Global_
    {
        return $this;
    }

    /**
     * @param Reflection\VariableDefinition $def
     */
    public function registerSuperGlobalVariableDefinition(Reflection\VariableDefinition $def): void
    {
        if ($def->getAccessor()->resolvable()) {
            $this->superGlobals[$def->getAccessor()->getPath()[0]->getName()] = true;
            $this->registerVariableDefinition($def);
        }
    }

    /**
     * @return array
     */
    public function getSuperGlobalVariables(): array
    {
        return array_filter(
            $this->variables,
            function ($name) {
                return isset($this->superGlobals[$name]);
            },
            ARRAY_FILTER_USE_KEY
        );
    }
}
