<?php

namespace MintyPHP\Tests\Architecture;

use PHPUnit\Framework\TestCase;

abstract class AbstractModuleRegistryContractTestCase extends TestCase
{
    protected string $fixturesDir;

    protected function setUp(): void
    {
        $this->fixturesDir = sys_get_temp_dir() . '/corecore-module-architecture-' . uniqid('', true);
        mkdir($this->fixturesDir, 0777, true);
    }

    protected function tearDown(): void
    {
        $this->removeDir($this->fixturesDir);
    }

    /**
     * @param array<string, mixed> $manifest
     */
    protected function createModuleManifest(string $dirName, array $manifest): void
    {
        $dir = $this->fixturesDir . '/' . $dirName;
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

        file_put_contents(
            $dir . '/module.php',
            '<?php return ' . var_export($manifest, true) . ';'
        );
    }

    private function removeDir(string $dir): void
    {
        if (!is_dir($dir)) {
            return;
        }

        $items = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS),
            \RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($items as $item) {
            if ($item->isDir()) {
                rmdir($item->getPathname());
                continue;
            }

            unlink($item->getPathname());
        }

        rmdir($dir);
    }
}
