<?php

namespace Intgrtn\Lib;

/**
 * @author heminei
 */
class Template
{

    private $file = null;
    private $html;
    private $variables = [];

    public function __construct($file = null)
    {
        if (!empty($file)) {
            $this->setFile($file);
        }
    }

    public function __set($name, $value)
    {
        $this->variables[$name] = $value;
    }

    public function __get($name)
    {
        if (isset($this->variables[$name])) {
            return $this->variables[$name];
        } else {
            return null;
        }
    }

    public function getFile()
    {
        return $this->file;
    }

    public function setFile($file)
    {
        if (!file_exists($file)) {
            throw new \ErrorException("File not found");
        }
        $this->file = $file;
        $this->html = file_get_contents($this->file);
    }

    public function parse()
    {
        $html = $this->html;

        foreach ($this->variables as $key => $value) {
            $tagToReplace = '{{' . $key . '}}';
            $html = str_replace($tagToReplace, $value, $html);
        }

        return $html;
    }

}
