1. Mateusz Łopaciński
  2. Ray

Source

Ray / Ray / View / Mustache.php

<?php

namespace Ray\View;

use Ray;

/**
 * Ray - micro framework for PHP
 * @author Mateusz Łopaciński <mateusz@robopuff.com> {@link http://robopuff.com}
 * @since 1.0.0
 * @version 1.0.0
 */
class Mustache implements Ray\View{

    /**
     * @var array
     */
    protected $options = array(
        'ext' => '.mustache',
        'layout' => 'default',
        'actionDir' => 'action',
        'action' => '404',
        'params' => array()
    );

    /**
     * @var array
     */
    protected $config;

    /**
     * @var Mustache\Compiler
     */
    protected $instance;

    /**
     * @param array $response
     * @param array $config
     */
    public function __construct(array $response, $config){

        $this->instance = new Ray\View\Mustache\Compiler();

        $this->options = array_merge($this->options, $response);

        $this->config = $config;

    }

    /**
     * Rendering process
     * @param null $layoutAsText
     * @param null $actionAsText
     * @return string
     * @throws \Ray\Exception\View\Mustache
     */
    public function render($layoutAsText=null, $actionAsText=null){

        $layout = $this->config['templates'] . DS . $this->options['layout'] . $this->options['ext'];

        $action = $this->config['templates'] . DS . $this->options['actionDir'] . DS . $this->options['action'] . $this->options['ext'];

        if($layoutAsText || file_exists($layout)){
            $template = ($layoutAsText) ? $layoutAsText : file_get_contents($layout);

            $params = is_array($this->options['params']) ? $this->options['params'] : array();

            $params['bodyID'] = $this->options['action'];

            if($actionAsText || file_exists($action)){
                $partial = array(
                    'action' => ($actionAsText) ? $actionAsText : file_get_contents($action)
                );

                return $this->instance->render($template, $params, $partial);
            }else{
                throw new Ray\Exception\View\Mustache('Action template file not found. Path: '. $action);
            }

        }else{
            throw new Ray\Exception\View\Mustache('Template file not found. Path: ' . $layout);
        }

        return;
    }

}