<?php
namespace common\modules\messageTemplate\components;


use common\modules\messageTemplate\models\MessageTemplate;
use yii\web\NotFoundHttpException;

/**
 * Class Templates
 * @package common\modules\messageTemplate\components
 *
 * @property MessageTemplate $template
 */
class Templates {
    protected $template;

    /**
     * @param $id
     * @param array $values
     * @throws \yii\web\NotFoundHttpException
     */
    public function __construct($id, $values=array()){
        /** @var MessageTemplate $model */
        $model = MessageTemplate::findOne($id);
        if ($model===null)
            throw new NotFoundHttpException('The requested page does not exist.');
        $this->template = $model->template;
        $this->setValues($values);
    }

    protected function setValues($values) {
        $pattern = '/\{(.*?)\}/';
        preg_match_all($pattern, $this->template, $result, PREG_PATTERN_ORDER);
        $pseudo_vars = $result[1];
        foreach($pseudo_vars as $key) {
            if (array_key_exists($key, $values)) {
                $this->template = str_replace('{'.$key.'}', $values[$key], $this->template);
            }
            if (array_key_exists(mb_strtolower($key), $values)) {
                $this->template = str_replace('{'.$key.'}', $values[mb_strtolower($key)], $this->template);
            }
        }
    }

    /**
     * @return MessageTemplate
     */
    public function getTemplate(){
        return $this->template;
    }
} 