<?php

namespace templates;

use Exception;

class TemplateLoader
{
    /**
     * @throws Exception
     */
    public static function load(string $template, array $data = []): string
    {
        $templatePath = realpath(TEMPLATES_PATH . '/' . $template . '.tpl');

        if (!str_starts_with($templatePath, TEMPLATES_PATH) && !file_exists($templatePath)) {
            throw new Exception('Invalid template path.');
        }

        $template = file_get_contents($templatePath);

        if (sizeof($data) > 0) {
            foreach ($data as $key => $value) {
                $template = str_replace('{{' . $key . '}}', $value, $template);
            }
        }

        return $template;
    }
}
