<?php

declare(strict_types=1);

namespace NoahVet\Reef\Domain\Tool;

class FileTool implements FileToolInterface
{
    public static function forceFilePutContents(string $filePath, mixed $contents): void
    {
        if (\str_starts_with($filePath, './')) {
            $filePath = \substr($filePath, 2);
        }

        $parts = \explode('/', $filePath);
        $file = \array_pop($parts);
        $directory = '';

        foreach ($parts as $part) {
            if (
                !\is_file($part)
                && !\is_dir($directory .= "$part/")
            ) {
                \mkdir($directory);
            }
        }

        \file_put_contents("$directory/$file", $contents);
    }

    public static function forceRemoveDirectory(string $directory): bool
    {
        try {
            /** @var array<string> $dir */
            $dir = \scandir($directory);
            foreach (\array_diff($dir, ['.', '..']) as $file) {
                (\is_dir("$directory/$file"))
                    ? self::forceRemoveDirectory("$directory/$file")
                    : \unlink("$directory/$file");
            }

            return \rmdir($directory);
        } catch (\Exception) {
            return false;
        }
    }
}
