<?php
namespace Installer;

class EnvWriter
{
    private string $rootPath;

    public function __construct(string $rootPath)
    {
        $this->rootPath = rtrim($rootPath, '/');
    }

    public function write(array $data): bool
    {
        $envFile = $this->rootPath . '/.env';

        $lines = [];
        foreach ($data as $key => $value) {
            $key = trim((string)$key);
            $value = str_replace('"', '\"', (string)$value);
            $lines[] = $key . '="' . $value . '"';
        }

        $content = implode(PHP_EOL, $lines) . PHP_EOL;
        return file_put_contents($envFile, $content) !== false;
    }
}
