<?php
/**
 * Mustache engine adapter
 * Implements the IView interface
 * @author Jérôme Brilland
 * @version 2.0
 * @copyright (c) 2018-2021, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class MustacheView implements IView {
    
    /**
     *
     * @var array
     * @access protected 
     */
    protected $data = [];
    
    /**
     *
     * @var Mustache_Engine 
     * @access private
     */
    private $mustache;
    
    /**
     * Class constructor
     * @access public
     */
    public function __construct() {
        $this->mustache = new Mustache_Engine([
            'loader' => new Mustache_Loader_CascadingLoader( [new Mustache_Loader_FilesystemLoader( 'public' . DS . TEMPLATES_DIR, ['extension' => 'html'] )] ),
            'partials_loader' => new Mustache_Loader_CascadingLoader( [new Mustache_Loader_FilesystemLoader( 'public' . DS . TEMPLATES_DIR, ['extension' => 'html'] )] ),
            'pragmas' => [Mustache_Engine::PRAGMA_FILTERS, Mustache_Engine::PRAGMA_BLOCKS]
        ]);
    }
    
    /**
     * 
     * @param string $name
     * @param mixed $value
     * @access public
     */
    public function assign( $name, $value ) {
        $this->data[$name] = $value;
    }
    
    /**
     * @param string $directory
     * @access public
     */
    public function addTemplateDirectory( $directory ) {
        $mustache = $this->mustache;
        $mustache->getLoader()->addLoader( new Mustache_Loader_FilesystemLoader( $directory, ['extension' => 'html'] ) );
        $mustache->getPartialsLoader()->addLoader( new Mustache_Loader_FilesystemLoader( $directory, ['extension' => 'html'] ) );
    }
    
    /**
     * Add a new Mustache helper.
     * @see Mustache_Engine::addHelper
     * @param string $name
     * @param mixed $helper
     * @access public
     */
    public function addHelper( $name, $helper ) {
        $this->mustache->addHelper( $name, $helper );
    }
    
    /**
     * Render a template
     * @param string $template Template
     * @param array $data
     * @return string Rendered template
     */
    public function render( $template, $data = null ) {
        $this->mustache->getLoader()->addLoader( new Mustache_Loader_StringLoader() );
        return $this->mustache->render( $template, array_merge( $this->data, $data ) );
    }
}
