<?php
/**
 * Latte template 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 LatteView implements IView {
    
    /**
     * @var Engine
     * @access private 
     */
    private $latte;
    
    /**
     * @var array
     * @access private 
     */
    private $parameters = [];

    /**
     * Class constructor
     * @access public
     */
    public function __construct() {
        $this->latte = new Latte\Engine();
        $this->latte->setLoader( new LatteCascadingLoader( [new LatteFileLoader( APP_DIR . TEMPLATES_DIR )] ) );
        if ( is_writable( VAR_DIR ) ) {
            $this->latte->setTempDirectory( VAR_DIR );
        }
        $this->latte->setAutoRefresh( true );
    }
    
    /**
     * 
     * @param string $name
     * @param mixed $value
     * @access public
     */
    public function assign( $name, $value ) {
        $this->parameters[$name] = $value;
    }
    
    /**
     * @param string $directory
     * @access public
     */
    public function addTemplateDirectory( $directory ) {
        $this->latte->getLoader()->addLoader( new LatteFileLoader( $directory ) );
    }
    
    /**
     * Registers run-time filter.
     * @param string $name
     * @param callable $callback
     */
    public function addFilter( $name, $callback ) {
        $this->latte->addFilter( $name, $callback );
    }

    /**
     * @return Latte\Engine
     * @access public
     */
    public function getLatte() {
        return $this->latte;
    }
    
    /**
     * Render a template
     * @param string $template Template
     * @param array $data
     * @return string Rendered template
     */
    public function render( $template, $data = null ) {
        return $this->latte->renderToString( $template, array_merge( $this->parameters, $data ) );
    }
}
