Advertisement
bueddl

Untitled

Sep 29th, 2013
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. /**
  4.  *
  5.  *
  6.  * @author Sebastian Büttner <sebastian.buettner@powerserverplus.net>
  7.  * @package void
  8.  * @version 1.0.0
  9.  * @copyright (c) 2013, powerserverplus.net
  10.  */
  11.  
  12. class FileNotFoundException extends Exception {}
  13.  
  14. class Template
  15. {
  16.     /**
  17.      * Whether to use debugging or not
  18.      */
  19.     const DEBUG = true;
  20.  
  21.     /**
  22.      * @var String Path to tempalte dir
  23.      */
  24.     const template_dir = 'templates';
  25.  
  26.     /**
  27.      * @var String (sub)template filename
  28.      */
  29.     protected $template = '';
  30.  
  31.     /**
  32.      * @var Array data to be used within the template
  33.      */
  34.     protected $data;
  35.  
  36.     /**
  37.      * Template constructor
  38.      *
  39.      * @param String $templ name of the template
  40.      */
  41.     public function __construct($templ, $layout = 'index')
  42.     {
  43.         $this->load($layout);
  44.  
  45.         $this->data = array();
  46.         $this->assign('subtemplate', $templ);
  47.     }
  48.  
  49.     /**
  50.      * Save a passed variable for later use in template
  51.      *
  52.      * @param String $name name of the varaible used to identify
  53.      * @param Mixed $value value to be assigned to the variable
  54.      */
  55.     public function assign($name, $value)
  56.     {
  57.         /* Separate name by dot */
  58.         $path = explode('.', $name);
  59.  
  60.         /* Take the last element of the array, as this is our final identifier */
  61.         $lastKey = array_pop($path);
  62.  
  63.         /* Create / fill array structure, start with the template`s data base array */
  64.         $parent = &$this->data;
  65.  
  66.         /* Iterate through the given name structure... */
  67.         foreach ($path as $key)
  68.         {
  69.             /* ...And create substructres where needed */
  70.             if (!isset($parent[$key]))
  71.                 $parent[$key] = array();
  72.  
  73.             /* Move the parent `pointer` deeper within the structure */
  74.             $parent = &$parent[$key];
  75.         }
  76.  
  77.         /* Finally assign the value to the deepest element in structure */
  78.         $parent[$lastKey] = $value;
  79.     }
  80.  
  81.     /*
  82.      *
  83.      */
  84.     public function phpize_var($var, $intend = false)
  85.     {
  86.         $php = '';
  87.  
  88.         switch ( gettype($var) )
  89.         {
  90.             case 'boolean':
  91.                 $php .= $var === true ? 'true' : 'false';
  92.  
  93.                 break;
  94.  
  95.             case 'integer':
  96.             case 'double':
  97.                 $php .= $var;
  98.  
  99.                 break;
  100.  
  101.             case 'string':
  102.                 $php .= "'" .
  103.                         str_replace("'", "\\'", $var) .
  104.                         "'";
  105.  
  106.                 break;
  107.  
  108.             case 'object':
  109.                 $php .= '(object)';
  110.             case 'array':
  111.                 $php .= 'array(' . ($intend ? "\n" : '') ;
  112.  
  113.                 foreach ($var as $key => $value)
  114.                 {
  115.                     $php .= $this->phpize_var($key, $intend) .
  116.                             ' => ' .
  117.                             $this->phpize_var($value, $intend) .
  118.                             ', ';
  119.  
  120.                     if ($intend)
  121.                         $php .= "\n";
  122.                 }
  123.  
  124.                 $php .= ')';
  125.  
  126.                 break;
  127.  
  128.             case 'NULL':
  129.                 $php .= 'NULL';
  130.  
  131.                 break;
  132.  
  133.             case 'resource':
  134.             default:
  135.  
  136.         }
  137.  
  138.         if ($intend)
  139.             $php = str_replace("\n", "\n  ", $php);
  140.  
  141.         return $php;
  142.     }
  143.  
  144.     /**
  145.      * Prepare and display the tempalte
  146.      *
  147.      */
  148.     public function display()
  149.     {
  150.         /* We start with no code */
  151.         $template_code = '';
  152.  
  153.         /* Merge template data with session-flash data */
  154.         $data = $this->data;
  155.  
  156.         if (isset($_SESSION['appends']) && is_array($_SESSION['appends']) && !empty($_SESSION['appends']))
  157.             $data = array_merge($data, $_SESSION['appends']);
  158.  
  159.         $_SESSION['appends'] = array();
  160.  
  161.         /* And iterate then over all passed variables, making them executable code again */
  162.         foreach ($data as $key => $value)
  163.         {
  164.             /* Secure that variables are valid for php */
  165.             if (! preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/ims', $key) )
  166.                 continue;
  167.  
  168.             /* Add a new line to the template code */
  169.             $template_code .=
  170.                 /* Write varaible name */
  171.                 '$' . $key . ' = ' . $this->phpize_var($value, true) . ';' . "\n";
  172.  
  173.         }
  174.  
  175.         $template_vars = $template_code;
  176.  
  177.         /* Put a php close tag, as we are continuing with out html-code-template */
  178.         $template_code .= '?>';
  179.  
  180.         /* Append the template */
  181.         $template_code .= file_get_contents($this->template);
  182.  
  183.         /* Execute the build string as PHP-Code */
  184.         eval($template_code);
  185.  
  186.         /* Debug */
  187.  
  188.         if (self::DEBUG)
  189.         {
  190.             echo "<div style='display: none; width: 80%; position: absolute; top: 50px; left: 50%; margin-left: -45%; background: url(/images/bg.png); z-index: 1001; border-radius: 8px; border: 4px solid #E6572C; padding: 30px; color: #555; text-shadow: 0 1px 1px #fff ' id='debug'>\n";
  191.             echo "<h3 style='font-style: normal; color: #E6572C; border-bottom: 2px solid #bbb; margin-bottom: 20px;'>Template vars:</h3><pre style='background: #ffffff; border-radius: 2px; border: 1px solid #aaa; padding: 5px; margin: 10px 0;'>" . ($template_vars) . "</pre>";
  192.             echo "</div>";
  193.         }
  194.         echo "<script type='text/javascript'>$(document).ready( function(){ $(document).keypress( function(e){ if (e.keyCode == 100) $('#debug').slideToggle() } ) } );</script>\n";
  195.     }
  196.  
  197.     /**
  198.      * Includes a given template by name
  199.      *
  200.      * @param String $templ the name of the tempalte file to be included
  201.      */
  202.     static function getInclude($templ)
  203.     {
  204.         /* Build the full path of the file to load */
  205.         $filename = Template::template_dir . '/' . $templ . '.template.php';
  206.  
  207.         /* Check whether the requested file does exist, if not throw exception */
  208.         if ( ! file_exists($filename) )
  209.             throw new FileNotFoundException('Template file ' . $filename . ' not found.');
  210.  
  211.         /* return the filename to include */
  212.         return $filename;
  213.     }
  214.  
  215.     /**
  216.      * Helper function, gives $default back when $var is unset
  217.      *
  218.      * @param Mixed $var
  219.      * @param Mixed $default
  220.      *
  221.      */
  222.     static function withDefault(&$var, $default)
  223.     {
  224.         if (!isset($var))
  225.             return $default;
  226.        
  227.         return $var;
  228.     }
  229.  
  230.     /**
  231.      * Try to load template by name, can throw FileNotFoundException
  232.      *
  233.      * @param String $templ template name
  234.      */
  235.     private function load($templ)
  236.     {
  237.         /* Build the full path of the file to load */
  238.         $filename = Template::template_dir . '/' . $templ . '.template.php';
  239.  
  240.         /* Check whether the requested file does exist, if not throw exception */
  241.         if ( ! file_exists($filename) )
  242.             throw new FileNotFoundException('Template file ' . $filename . ' not found.');
  243.  
  244.         /* Set the filename of the template */
  245.         $this->template = $filename;
  246.     }
  247.  
  248.  
  249. }
  250.  
  251. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement