<?php
namespace library;

/**
 * Add extra macros for Latte
 * Implements the IFilter interface
 * @author Jerôme Brilland
 * @version 2.0
 * @copyright (c) 2019-2021, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class CMSMacrosFilter implements \IFilter {
  
	/**
	 * @param Request request Request object
	 * @param Response response Response object
	 * @access public
	 */
	public function execute( \Request $request, \Response $response, \FilterChain $filterchain ) {
        \IoC::resolve( 'eventmediator' )->attach( 'before_render', function( $controller, $request, $response ) {
            $latte = \IoC::resolve( 'view' )->getLatte();
            $set = new \Latte\Macros\MacroSet( $latte->getCompiler() );

            $set->addMacro(
                'snippet',
                '$snippet = models\\Snippet::findOne( [\'name\' => %node.word] );',
                'unset( $snippet )'
            );

            $set->addMacro(
                'snippetContent',
                'echo IoC::resolve( \'texy\')->process( models\\Snippet::findOne( [\'name\' => %node.word] )->content );'
            );

            $set->addMacro(
                'siteTitle',
                'echo IoC::resolve( \'settings\')[\'site_title\'];'
            );

            $set->addMacro(
                'executionTime',
                'echo microtime( true ) - START_TIME;'
            );

            return true;
        } );
        
		$filterchain->execute( $request, $response );
	}
}
