<?php

namespace MintyPHP\Tests\Support;

use MintyPHP\App\AppContainer;

trait AppContainerIsolationTrait
{
    private mixed $appContainerIsolationPrevious = null;
    private bool $appContainerIsolationActive = false;

    protected function pushAppContainer(AppContainer $container): void
    {
        if (!$this->appContainerIsolationActive) {
            $this->appContainerIsolationPrevious = $GLOBALS['minty_app_container'] ?? null;
            $this->appContainerIsolationActive = true;
        }

        $GLOBALS['minty_app_container'] = $container;
    }

    protected function restoreAppContainer(): void
    {
        if (!$this->appContainerIsolationActive) {
            return;
        }

        if ($this->appContainerIsolationPrevious instanceof AppContainer) {
            $GLOBALS['minty_app_container'] = $this->appContainerIsolationPrevious;
        } else {
            unset($GLOBALS['minty_app_container']);
        }

        $this->appContainerIsolationPrevious = null;
        $this->appContainerIsolationActive = false;
    }
}
