<?php

abstract class Snippets
{
    protected $snippets;
    protected $snippetsPath;
    protected $preventOutput;

    public function __construct()
    {
        //$this->snippetsPath = realpath(__DIR__ . '/../snippets/');
        $this->snippetsPath = realpath(PROJECT_DIR . '/snippets');

        $this->preventOutput = false;
    }

    final public function run()
    {
        if (!is_array($this->snippets))
            $this->getSnippets();
            
		try {
            for ($i=0, $j=count($this->snippets); $i<$j; $i++) {
				$this->runSnippet($i);
			}
		} catch (Exception $e) {
			throw $e;
		}
    }

	final protected function runSnippet($snippetIdx)
	{
        if ($this->snippets[$snippetIdx]['file']) {
            $filename = $this->snippetsPath . '/' . $this->snippets[$snippetIdx]['file'];
            if (!is_file($filename))
                throw new Exception('No snippet file! ' . $filename);
            include_once $filename;
            $funcname = 'snippet_' . $this->snippets[$snippetIdx]['fn'];
            //if (!function_exists($funcname))
            //    throw new Exception('No snippet function! ' . $funcname);
        } else {
            $funcname = $this->snippets[$snippetIdx]['fn'];
        }

        if (!is_callable($funcname))
            throw new Exception('Snippet is not callable! [' . print_r($funcname, true) . ']');
        
		// Возможно сделать обёртку в ob_*,  что бы не засорять вывод?
		call_user_func($funcname, $this);
	}
    
    abstract protected function getSnippets();
    

    public function isOutputPrevented($is=null)
    {
        if ($is===null) {
            return $this->preventOutput;
        } else {
            $this->preventOutput = $is?true:false;
        }
    }
    
}





//class SnippetRunResult
//{
//
//    public function __construct($options)
//    {
//        
//    }
//
//
//
//}

?>