<?php
/**
 * Medoo template loader
 * Implements Latte\ILoader
 * @author Jérôme Brilland
 * @version 2.0
 * @copyright (c) 2020-2021, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class LatteDatabaseLoader implements Latte\ILoader {

    /**
     * @var Medoo
     * @access protected
     */
    protected $database;

    /**
     * @var string
     * @access private
     */
    private $tableName;

    /**
     * Class constructor
     * @param Medoo $database
     * @param string $tableName
     * @access public
     */
    public function __construct( $database, $tableName = 'template' ) {
        $this->database = $database;
        $this->tableName = $tableName;
    }

    /**
	 * Returns template source code.
	 * @return string
     * @access public
	 */
	public function getContent( $name ) {
        $content = $this->getValue( 'content', $name );
        if ( empty( $content ) ) {
            throw new RuntimeException( sprintf( 'Template "%s" does not exist.', $name ) );
        }
        return $content;
    }

	/**
	 * Checks whether template is expired.
	 * @return bool
     * @access public
	 */
	public function isExpired( $name, $time ) {
        return $this->getValue( 'last_modified', $name ) > $time;
    }

	/**
	 * Returns referred template name.
	 * @return string
     * @access public
	 */
	public function getReferredName( $name, $referringName ) {
        return $name;
    }

	/**
	 * Returns unique identifier for caching.
	 * @return string
     * @access public
	 */
	public function getUniqueId( $name ) {
        $value = $this->getValue( 'template_id', $name );
        if ( empty( $value ) ) {
            throw new RuntimeException( sprintf( 'Template "%s" does not exist.', $name ) );
        }
        return 'database/' . $name;
    }

    protected function getValue( $column, $name ) {
        return $this->database->get( $this->tableName, $column, ['name' => $name] );
    }
}
