<?php

/**
 * A cascading loader for Latte
 * Implements Latte\ILoader
 * @author Jérôme Brilland
 * @version 1.1.1
 * @copyright (c) 2019-2021, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class LatteCascadingLoader implements Latte\ILoader {

    private $loaders = [];

    /**
     * Class constructor
     * @param array $loaders
     * @access public
     */
    public function __construct( array $loaders = [] ) {
        foreach ( $loaders as $loader ) {
            $this->addLoader( $loader );
        }
    }

    /**
     * Add a loader instance
     * @param Latte\ILoader $loader
     * @access public
     */
    public function addLoader( Latte\ILoader $loader ) {
        $this->loaders[] = $loader;
    }

    /**
     * Returns template source code
     * @param string $name
     * @return string
     * @throws RuntimeException
     * @access public
     */
    public function getContent( $name ) {
        foreach ( $this->loaders as $loader ) {
            try {
                return $loader->getContent( $name );
            } catch ( RuntimeException $e ) {
                
            }
        }
        throw new RuntimeException( sprintf( 'Template "%s" does not exist.', $name ) );
    }
    
    /**
     * Checks whether template is expired.
     * @param string $name
     * @param int $time
     * @return boolean
     * @access public
     */
    public function isExpired( $name, $time ) {
        foreach ( $this->loaders as $loader ) {
            if ( $loader->isExpired( $name, $time ) ) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * Returns referred template name.
     * @param string $name
     * @param string $referringName
     * @return string
     * @access public
     */
    public function getReferredName( $name, $referringName ) {
        return $name;
    }
    
    /**
     * Returns unique identifier for caching.
     * @param string $name
     * @return string
     * @access public
     */
    public function getUniqueId( $name ) {
        foreach ( $this->loaders as $loader ) {
            try {
                return $loader->getUniqueId( $name );
            } catch ( RuntimeException $e ) {
                
            }
        }
        throw $e;
    }

}
