昨夜渡轮 发表于 2011-3-22 22:32:49

给CI模板解析类Parser增加if逻辑判断功能

本帖最后由 昨夜渡轮 于 2011-3-22 22:35 编辑

CI本身的模板解析类不支持条件判断在网上找了二个大家来学习改进一下
代码一:

<?phpif (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* @package      CodeIgniter
* @author      Rick Ellis
* @copyright    Copyright (c) 2006, EllisLab, Inc.
* @license      http://www.codeignitor.com/user_guide/license.html
* @link      http://www.codeigniter.com
* @since      Version 1.0
* @filesource
* MY Parser Class
*
* 增加if判断功能
*/
class MY_Parser extends CI_Parser{
   /**
   *Parse a template
   *
   * Parses pseudo-variables contained in the specified template,
   * replacing them with the data in the second param
   *
   * @access    public
   * @param    string
   * @param    array
   * @param    bool
   * @param    bool
   * @return    string
   */
    function parse($template, $data, $return = FALSE, $show_errors = FALSE)
    {
      $CI =& get_instance();
      $template = $CI->load->view($template, $data, TRUE);
      if ($template == '')
      {
            return FALSE;
      }
      foreach ($data as $key => $val)
      {
            if (is_array($val))
            {
                $template = $this->_parse_pair($key, $val, $template);
            }
            else
            {
                $template = $this->_parse_single($key, (string)$val, $template);
            }
      }
      // Check for conditional statments
      $template = $this->conditionals($template, $show_errors);
      // Should we show template errors?
      if (!$show_errors)
      {
            if (preg_match_all("(".$this->l_delim."([^".$this->r_delim."/]*)".$this->r_delim.")", $template, $m))
            {
                foreach($m as $value)
                {
                  $template = preg_replace('#'.$this->l_delim.$value.$this->r_delim.'(.+)'.$this->l_delim.'/'.$value.$this->r_delim.'#sU', "", $template);
                  $template = str_replace ("{".$value."}", "", $template);
                }
            }
      }
      if ($return == FALSE)
      {
            $CI->output->final_output = $template;
      }
      return $template;
    }
    // --------------------------------------------------------------------
    /**
   *Parse conditional statments
   * Note: This function will ignore no matched or conditional statments with errors
   *
   * @access    public
   * @param    string
   * @param    bool
   * @return    string
   */
    function conditionals($template, $show_errors)
    {
      if (preg_match_all('#'.$this->l_delim.'if (.+)'.$this->r_delim.'(.+)'.$this->l_delim.'/if'.$this->r_delim.'#sU', $template, $conditionals, PREG_SET_ORDER))
      {
            if(count($conditionals) > 0)
            {
                foreach($conditionals AS $condition)
                {
                  $raw_code = (isset($condition)) ? $condition : FALSE;
                  $cond_str = (isset($condition)) ? $condition : FALSE;
                  $insert = (isset($condition)) ? $condition : '';
                  if(!preg_match('/('.$this->l_delim.'|'.$this->r_delim.')/', $cond_str, $problem_cond))
                  {
                        // If the the conditional statment is formated right, lets procoess it!
                        if(!empty($raw_code) OR $cond_str != FALSE OR !empty($insert))
                        {
                            // Get the two values
                            $cond = preg_split("/(\!=|==|<=|>=|<>|<|>|AND|XOR|OR|&&)/", $cond_str);
                            // Do we have a valid if statment?
                            if(count($cond) == 2)
                            {
                              // Get condition
                              preg_match("/(\!=|==|<=|>=|<>|<|>|AND|XOR|OR|&&)/", $cond_str, $cond_m);
                              array_push($cond, $cond_m);
                              // Remove quotes - they cause to many problems!
                              $cond = preg_replace("/[^a-zA-Z0-9s]/", "", $cond);
                              $cond = preg_replace("/[^a-zA-Z0-9s]/", "", $cond);
                              // Test condition
                              eval("\$result = (\"".$cond."\" ".$cond." \"".$cond."\") ? TRUE : FALSE;");
                            }
                            else
                            {
                              $result = (isset($data[$cond_str])) ? TRUE : FALSE;
                            }
                        }
                        // If the condition is TRUE then show the text block
                        $insert = preg_split('#'.$this->l_delim.'else'.$this->r_delim.'#sU', $insert);
                        if($result == TRUE)
                        {
                            $template = str_replace($raw_code, $insert, $template);
                        }
                        else
                        {
                            // Do we have an else statment?
                            if(is_array($insert))
                            {
                              $insert = (isset($insert)) ? $insert : '';
                              $template = str_replace($raw_code, $insert, $template);
                            }
                            else
                            {
                              $template = str_replace($raw_code, '', $template);
                            }
                        }
                  }
                  elseif(!$show_errors)
                  {
                        // Remove any if statments we can't process
                        $template = str_replace($raw_code, '', $template);
                  }
                }
            }
      }
      return $template;
    }
    // --------------------------------------------------------------------
}

使用方法:

{if true}
ok
{else}
no
{/if}


代码二:

<?phpif ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* COMPER Template Parser Class
*
* Parsing templates
*
* @framework CodeIgniter
* @subpackage Libraries
* @authorTomáš Bončo
* @category Parser
* @year      2010
* @version   1.5.1
*/
class Parser {
    var $file; // file (with path)
var $values = array(); // pseudo-variables
var $blocks = array(); // cycles
var $conditions = array(); // conditions
var $content; // output
var $clean; // cleaning of pseudo-variables
var $show; // showing parsered template
var $theme; // theme
    var $theme_Original;
    var $CI; // codeigniter instance
    var $append_function = array();
    var $debug_messages = array // debug levels: 0 - No debugging, 1 - Critical Errors, 2 - TPL errors, 3 - PHP errors, 4 - Debugging
   (
      0 => array ('debug_level' => 1, 'message' => "I can't find defined theme!"), // line 73
      1 => array ('debug_level' => 3, 'message' => "Wrong parameters in calling Append fuction!"), // line 93
      2 => array ('debug_level' => 1, 'message' => "Wrong input parameters in calling Parse function!"), // line 130
      3 => array ('debug_level' => 1, 'message' => "File %s not found!"), // line 201
      4 => array ('debug_level' => 2, 'message' => "File %s is empty!"), // line 195
      5 => array ('debug_level' => 2, 'message' => "Missing <!-- END --> for your condition!"), // line 429
      6 => array ('debug_level' => 2, 'message' => "Missing <!-- END --> for your condition: <!-- IF %s -->!"), // line 350
      7 => array ('debug_level' => 3, 'message' => "Wrong parameters in appending!"), // line 496
      8 => array ('debug_level' => 3, 'message' => "SplitPage error (function SplitPage is used by Blocks)!"), // line 546
      9 => array ('debug_level' => 3, 'message' => "Check your condition. Condition: %d"), // line 546
);

var $debug_log_level = 3;
var $debug_show_level = 1;
var $debug_status = 'inactive';
   
   
    function Parser()
    {
      /* CI instance */
      $this->CI =& get_instance();
      $this->CI->load->helper('file');
      $this->CI->load->library('unit_test');
      
      log_message('debug', 'COMPER Template Parser Class Initialized');
    }
   
    ###########################
###
### Theme
###
###########################
   
    public function theme($value)
    {
   $this->CI->unit->run($value, 'is_string', 'Testing input of theme function');
   
      if (is_dir(APPPATH.'views/'.$value))
      {
            $this->theme_Original = $value; /** Saving for Includes **/
            $this->theme = $value.'/tpl/';
            $this->CI->config->set_item('comper_parser', array('theme' => $value));
            
            return TRUE;
      }
      
      else
      {
         $this->_debug(0);
      }
      
      return FALSE;
    }
   
    ###########################
###
### Append
###
###########################
   
    public function append($name, $array)
    {
   $this->CI->unit->run($name, 'is_string', 'Testing input "name" of append function');
   $this->CI->unit->run($array, 'is_array', 'Testing input "array" of append function');
   
   if ( ! empty($name) && is_array($array))
{
      $this->append_function[$name] = $array;
   }
   else
   {
      $this->_debug(1);
   }
    }
   
    ###########################
###
### Debug
###
###########################
   
    public function debug()
    {
   $this->CI->unit->active(TRUE);
   $this->debug_status = 'started';
    }
   
    private function _debug($id, $param1 = null, $param2 = null, $param3 = null)
    {
   if ($this->debug_messages[$id]['debug_level'] <= $this->debug_log_level)
   {
      log_message('error', 'COMPER Template Parser: ' . sprintf($this->debug_messages[$id]['message'], $param1, $param2, $param3));
   }

   if ($this->debug_messages[$id]['debug_level'] <= $this->debug_show_level)
   {
      $message = sprintf($this->debug_messages[$id]['message'], $param1, $param2, $param3);
      
      if ($this->debug_status == 'started') $message .= '<br><br><h2>Debugging</h2>' . $this->CI->unit->report();
      show_error('COMPER Template Parser: ' . $message);
   }
    }
    /**
   * parse( $template , $data , $config )
   *
   *
   * @template - string - name of the template without extension, example: welcome
   * @data - array - contents pseudo-variables, cycles, conditions -
   * @config - array - posible values:
   *      @show - bool - if the parsered text will be apended to Output class - default TRUE
   *      @clean - bool - if unused pseudo-variables will be deleted (cleaned) - default TRUE
   *      @theme - string - you can set theme this way too
   *      @extension - string - contents file extension - default tpl
   *      @exception - array - if we don't want to delete some pseudo-variables (because of Benchmark Class for example)
   *      @append - array - if we want to add some special values like language, config, and so on.
   *
    **/
   
    public function parse($template, $data = array(), $config = array())
    {
   log_message('debug', 'COMPER Template Parser Class start parsering');
   
   $this->CI->unit->run($config, 'is_array', 'Testing input "config" of append function');
   $this->CI->unit->run($template, 'is_string', 'Testing input "template" of parse function');
   $this->CI->unit->run($data, 'is_array', 'Testing input "data" of append function');
   
   if (( ! empty($config) && !is_array($config))){ $this->_debug(2); return FALSE; }
   
   ######################################################################
   $ci_debug = $this->CI->config->item('comper_parser');    ##
                      ##
   if ( isset ($config['debug_show_level']))       ##
   {               ##
      $this->debug_show_level = $config['debug_show_level'];   ##
   }               ##############
                      ##    ##
   else                ##DEBUG ##
   {               ##CONFIG ##
      if ( isset ($ci_debug['debug_show_level']))      ##   ##
      {                ##############
       $this->debug_show_level = $ci_debug['debug_show_level']; ##
      }                ##
   }               ##
                     ##
if ( isset ($config['debug_log_level']))       ##
   {               ##
      $this->debug_show_level = $config['debug_log_level'];   ##
   }               ##############
                   ##    ##
   else                ##DEBUG ##
   {               ##CONFIG ##
      if ( isset ($ci_debug['debug_log_level']))      ##   ##
      {                ##############
       $this->debug_show_level = $ci_debug['debug_log_level'];##
      }                ##
   }               ##
                     ##
   if ($this->debug_show_level == 4) $this->debug();   ##
   ######################################################################
   
   
      
      if (( ! empty($template) && !is_string($template)) || ( ! empty($data) && !is_array($data)) || empty($template))
{
            $this->_debug(2);
            
            return FALSE;
      }   
      
      if ( empty($data)) $data = array();
      if ( empty($config)) $config = array();
      
      foreach ($data as $name => $value)
      {
            if (is_array($value))
            {
                $this->blocks[$name] = $value;
            }
            
            elseif (is_bool($value))
            {
                $this->conditions[$name] = $value;
            }
            
            else
            {
                $this->values[$name] = $value;
            }
      }
               
      /* Config */      
      
      $this->data = $data;
      $this->config = $config;
      $this->_config($this->config);
               
      /* File and folder path */
      $this->file = APPPATH . 'views/' . $this->theme . $template . '.' . $this->extension;
      $this->folder = $this->_Path() . 'views/' . $this->theme_Original;      
      
      /* Other*/
      
      $this->values['T_Folder'] = $this->folder;
      
      if ($this->content = read_file($this->file) ) // open the file
      {      
            if (strlen($this->file) > 0)
            {
            
                $pattern = array("\n", "\r", "\t");
                $pattern2 = array('°°°°°°', 'ˇˇˇˇˇˇ', '´´´´´´');               
               
       $this->content = str_replace($pattern, $pattern2, $this->content);
               
       $this->_includes();
       $this->_blocks();
       $this->_conditions();
       $this->_values();
               
                $this->content = str_replace($pattern2,$pattern,$this->content);
                              
       $this->_show();
               
    if ($this->debug_status == 'started') echo $this->CI->unit->report();
                log_message('debug', 'COMPER Template Parser Class end parsering');
               
                return $this->content;                              
            }
            
            else
            {
             $this->_debug(4, $this->file);
            }
      }
      
      else
      {
            $this->_debug(3, $this->file);
            return FALSE;
      }

if ($this->debug_status == 'started') echo $this->CI->unit->report();

log_message('debug', 'COMPER Template Parser Class start parsering');
    }
   
   
    ###
### Config
###
   
   private function _config($config)
   {
      $this->CI->unit->run($config, 'is_array', 'Testing input "config" of _config function (user input when calling parse)');
      
      $ci_config = $this->CI->config->item('comper_parser');
      $config = ( ! empty($ci_config)) ? $config + $ci_config : $config; // loading config from config.php
      
      $default_values = array
      (
            'show'=> TRUE,
            'clean' => TRUE,
            'extension' => 'tpl',
            'exception' => array('memory_usage', 'elapsed_time'),
            'append' => array
                            (
                              'config' => $this->is_not_empty($this->CI->config->config, array()),
                              'lang'   => $this->is_not_empty($this->CI->lang->{'language'}, array())
                            )
      );
      
      $this->show       = (isset($config['show']) && $config['show'] === FALSE)? $config['show'] : $default_values['show'];
      $this->clean      = (isset($config['clean']) && $config['clean'] === FALSE)? $config['clean'] : $default_values['clean'];
      $this->extension= ( ! empty($config['extension']) && is_string($config['extension'])) ? $config['extension'] : $default_values['extension'];
      $this->exceptions = ( ! empty($config['exception']) && is_array($config['exception']))? $config['exception'] + $default_values['exception'] : $default_values['exception'];
      $this->appends    = ( ! empty($config['append'])    && is_array($config['append']))   ? $config['append'] + $default_values['append'] : $default_values['append'];
      $this->appends+= $this->append_function;
      
      if ( ! empty($config['theme'])) $this->theme($config['theme']);
    }

###
### Includes
###

private function _includes()
    {
$a_Include = preg_split('#<!--[[:space:]]*INCLUDE[[:space:]]*(.*?)[[:space:]]*-->#i', $this->content, '-1', PREG_SPLIT_DELIM_CAPTURE );
if (Count($a_Include) > 0)
      {
            $p_parser = new Parser;
   for ($i = 0; $i < Count($a_Include); $i++)
            {
    if ($i % 2 !== 0)
                {
                  $config = array(
                        "theme" => $this->theme_Original,
                        "show"=> FALSE
                  );
                  
   $a_Include[$i] = $p_parser->parse($a_Include[$i], $this->data, $this->config + $config);
                }
   }
}

$this->content = implode('', $a_Include);
if (preg_match('#<!--[[:space:]]*INCLUDE[[:space:]]*(.*?)[[:space:]]*-->#im', $this->content) > 0) $this->_includes();
}

###
### Blocks (Cycles)
###
private function _blocks()
    {
$a_Blocks = preg_split('#<!--[[:space:]]*BEGIN[[:space:]]*(.*?)[[:space:]]*-->(.+?)<!--[[:space:]]*END[[:space:]]*\\1[[:space:]]*-->#im', $this->content, '-1', PREG_SPLIT_DELIM_CAPTURE ); // Make array from template         
      
      if (is_array($a_Blocks) && Count($a_Blocks) > 0)
      {
            $a_Page = $this->_splitPage($a_Blocks);
            
            $a_Identifikator_Cyklu = $a_Page;    // Contains identificator and it's position in (array) $a_Blocks
            $a_Content = $a_Page;                // Contains position (in array) and content of current cycle
      
   if (is_array($a_Identifikator_Cyklu) && Count($a_Identifikator_Cyklu) > 0)
            {   
       foreach ($a_Identifikator_Cyklu as $r_Identifikator_Cyklu => $r_Pozicia)
                {
      $r_ReplaceText = NULL;
      $r_Identifikator_Cyklu = reset(explode('|´#´|', $r_Identifikator_Cyklu));
      
      if ( ! empty($this->blocks[$r_Identifikator_Cyklu]))
                  {   
         foreach ($this->blocks[$r_Identifikator_Cyklu] as $r_Nazov_Premennej => $a_Hodnota_Premennej)
                        {
                         $this->CI->unit->run($r_Nazov_Premennej, 'is_string', 'Testing input "r_Nazov_Premennej" of _blocks function');
         $this->CI->unit->run($a_Hodnota_Premennej, 'is_array', 'Testing input "r_Hodnota_Premennej" of _blocks function');
         
          $r_ReplaceText .= $a_Content[$r_Pozicia+1];
                           
       foreach ($this->blocks[$r_Identifikator_Cyklu][$r_Nazov_Premennej] as $r_Nazov => $r_Hodnota)
                            {
                           $this->CI->unit->run($r_Nazov, 'is_string', 'Testing input "r_Nazov" of _blocks function');
         $this->CI->unit->run($r_Hodnota, 'is_string', 'Testing input "r_Hodnota" of _blocks function');
         
      $r_ReplaceText = str_replace('{'. $r_Nazov .'}', $r_Hodnota, $r_ReplaceText);
                              
                              /* RESET */
                              $r_Nazov = NULL;
                              $r_Hodnota = NULL;
       }
         }
                        
         $a_Blocks[$r_Pozicia] = NULL; // delete identificator
         $a_Blocks[$r_Pozicia+1] = $r_ReplaceText; // old content replace new one
         $r_ReplaceText = NULL; // reset 'cause of next cycle
      }
   
   else /* If is cycle defined in .tpl but not in .php */
                  {
         $a_Blocks[$r_Pozicia] = NULL; // delete identificator
         $a_Blocks[$r_Pozicia+1] = NULL; // delete content
                  }   
                }
            
       $this->content = implode('', $a_Blocks);
      
                if (preg_match('#<!--[[:space:]]*BEGIN[[:space:]]*(.*?)[[:space:]]*-->(.+?)<!--[[:space:]]*END[[:space:]]*\\1[[:space:]]*-->#im', $this->content) > 0) $this->_blocks();
            }
      }
}

###
### Conditions
###

private function _conditions()
{
preg_match_all("#<!--[[:space:]]*IF[[:space:]]*(.*?)[[:space:]]*-->#im", $this->content, $if_preg, PREG_OFFSET_CAPTURE ); // zistime prítomnosť všetkých IF v texte

if (count($if_preg) > 0)
{
   $if_preg_rev = array(array_reverse($if_preg), array_reverse($if_preg));
   $this->content_length = strlen($this->content);

   foreach ($if_preg_rev as $index => $item) // prejdeme celý strom podiemnok
   {
    preg_match_all("#<!--[[:space:]]*END[[:space:]]*-->#im", $this->content, $end_preg, PREG_OFFSET_CAPTURE ); // zistime prítomnosť všetkých END v texte
    preg_match_all("#<!--[[:space:]]*ELSEIF[[:space:]]*(.*?)[[:space:]]*-->#im", $this->content, $elseif_preg, PREG_OFFSET_CAPTURE ); // zistime prítomnosť všetkých ELSEIF v texte
    preg_match_all("#<!--[[:space:]]*ELSE[[:space:]]*-->#im", $this->content, $else_preg, PREG_OFFSET_CAPTURE ); // zistime prítomnosť všetkých ELSE v texte
   
    if (count($end_preg > 0))
    {
   $ending = $this->_find($end_preg, $item, $this->content_length); // získame všetky END
   
   if (empty($ending))
   {
      $this->_debug(6, ($if_preg_rev[$index]));
   }
   
   else
   {
      $end_tag = $ending;
   
      $inside_elseif = $this->_find($elseif_preg, $item, $end_tag); // zistíme prítomnosť ELSEIF v danom rozsahu IF-END
      $inside_else = $this->_find($else_preg, $item, $end_tag); // zistíme prítomnosť END v danom rozsahu IF-END
      
      // ------------------------------------------------
   
      if ( $this->_statement($if_preg_rev[$index]) )
      {
       if (count($inside_elseif) == 0 && count($inside_else) == 0) // pokiaľ IF-END neobsahuje ELSEIF alebo ELSE
       {
      $pos_next_element = $end_tag;
       }
      
       else
       {
      $pos_next_element = (count($inside_elseif) !== 0) ? $inside_elseif : $inside_else; // zistíme pozíciu nasledujúceho prvku
       }
      
       $content = substr($this->content, ($item + strlen($item)), ($pos_next_element - ($item + strlen($item))));
      }
      
      else
      {
       $elseif_founded = FALSE;
      
       if (count($inside_elseif) !== 0) // pokiaľ sú ELSEIF
       {
      foreach ($inside_elseif as $id => $element) // tak prejdeme každé jedno
      {
         if ( $this->_statement($elseif_preg[$element]) ) // zistíme či je pravidvé
         {
          if ($id !== (count($inside_elseif)-1)) // pokiaľ je posledný ELSEIF
          {
         $content = substr($this->content, ($element + strlen($element)), ($inside_elseif[$id+1] - ($element + strlen($element))));
          }
         
          else
          {
         $pos_next_element = (count($inside_else) == 0) ? $end_tag : $inside_else;
         $content = substr($this->content, ($element + strlen($element)), ($pos_next_element - ($element + strlen($element))));
          }
         
          $elseif_founded = TRUE;
         
          break;
         }
      }
       }
      
       if ($elseif_founded == FALSE) // riešime ELSE
       {
      if (count($inside_else) !== 0)
      {
         $content = substr($this->content, ($inside_else + strlen($inside_else)), ($end_tag - ($inside_else + strlen($inside_else))));
      }
      
      else
      {
         $content = null;
      }
       }
      }
   
      $this->content = $this->_str_change($this->content, $content, $item, ($end_tag + strlen($end_tag))); // urobíme zmenu
      
      // ------------------------------------------------
      
      unset($end_preg[$end_tag]);
   }
    }
   
    else
    {
   $this->_debug(5);
    }
   }
}
}

###
### Values
###

private function _values()
    {
   $this->CI->unit->run($this->values, 'is_array', 'Testing global input "values"');
   $this->CI->unit->run($this->exceptions, 'is_array', 'Testing global input "exceptions"');
   $this->CI->unit->run($this->appends, 'is_array', 'Testing global input "appends"');
   
   if (is_array($this->values) && Count($this->values) > 0)
      {
      foreach ($this->values as $r_Key => $r_Value)
            {
       $r_Value = str_replace( array('{', '}'), array('&{&&;', '&}&&;' ), $r_Value);
       $this->content = str_replace('{'. $r_Key .'}', $r_Value, $this->content);
      }
      }
      
      foreach ($this->exceptions as $exception)
      {
         $this->CI->unit->run($exception, 'is_string', 'Testing input "exception" of _exception function');
         
         if (is_string($exception))
            $this->content = str_replace('{'. $exception .'}', '&{&&;' . $exception . '&}&&;', $this->content);
      }
      foreach ($this->appends as $append_name => $append_value)
      {
         $this->CI->unit->run($append_name, 'is_string', 'Testing input "append_name" of _values function');
         $this->CI->unit->run($append_value, 'is_array', 'Testing input "append_value" of _values function');
         
            $this->_append($append_name, $append_value);
}
      
if ( ! is_bool($this->clean)) $this->clean = TRUE;
      if ($this->clean) $this->content = preg_replace('#{([^[:space:]\:\{\}\=\+\;]+)}#', '', $this->content);
      
$this->content = str_replace('&{&&;','{',$this->content);
$this->content = str_replace('&}&&;','}',$this->content);
}

###
### Append
###

private function _append($name, $array, $parents = NULL)
    {
   if ( !empty($name) && is_array($array))
{
         foreach($array as $array_name => $array_value)
         {
             if (is_array($array_value))
    {
               $parents = $parents . $array_name . '->';
               $this->_append($name, $array_value, $parents);
               $parents = NULL;
             }
            
             else
             {
               $this->content = preg_replace("#\{". $name .":(([[:space:]])*". $parents .")*([[:space:]])*". $array_name ."\}#", $array_value, $this->content);
             }
         }
         
         $parents = NULL;
      }
      
      else
      {
         $this->_debug(7);
      }
    }

###
### @Show
###

    private function _show()
    {
      if ( ! is_bool($this->show)) $this->show = TRUE;   
   if ($this->show) $this->CI->output->append_output($this->content);      
    }
   


###########################
###
### Helpers
###
###########################
private function _Path()    // used in opening the file
    {
      if (($_SERVER['SERVER_NAME'] == 'localhost' || $_SERVER['SERVER_ADDR'] == '127.0.0.1' || $_SERVER['REMOTE_ADDR'] == '127.0.0.1') && strpos(APPPATH, BASEPATH) !== FALSE)
      return $this->CI->config->item('base_url') . end(explode('/', substr(BASEPATH, 0, -1))) . '/' . end(explode('/', substr(APPPATH, 0, -1))) . '/';
      
else return APPPATH;
    }
    private function _splitPage($array)// used by Blocks
    {
   if (is_array($array))
   {
         $a_Identifikator_Cyklu = array();
         $a_Content = array();
         $i = 0;
               
         foreach ($array as $r_ArrayName => $r_ArrayValue)
         {
             $r_LocalInfo = round(($r_ArrayName/3)*10);
             $r_LocalInfo = substr($r_LocalInfo, -1); /* získame buď 1, 3 alebo 7 */
                        
             if ($r_LocalInfo == 3) $a_Identifikator_Cyklu[$r_ArrayValue. '|´#´|' . $i] = $r_ArrayName;
       elseif ($r_LocalInfo == 7) $a_Content[$r_ArrayName] = $r_ArrayValue;
         
       $i++;
                        
             /*
               Everything is a cycle of 3 parts:
                0 - before (cycle)
                1 - identificator (of cycle)
                2 - content (of cycle)
             */
      }
   
         return array($a_Identifikator_Cyklu, $a_Content);
      }
      $this->_debug(8);
    }
   
    private function is_not_empty(&$value, $return = NULL)// used in config
    {
      if ( ! empty ($value)) return $value;
      else return $return;
    }
/**
*
* Nájde všetky deti (ELSE a ELSEIF) v rozsahu zadaných pozícií .. teda od povedzme 7 pozície do 56 pozície v reťazci
*
* */

private function _find($array, $from, $to = 0)    // used by conditions
{
$output = array();

foreach ($array as $index => $item)
{
   if ( ($item > $from) && ($item < $to) )
   {
    $output[] = $item + array('3' => $index);
   }
}

return $output;
}

/**
*
* Nahradí všetko od pozície A po pozíciu B v danom reťazci iným reťazcom
*
* */

private function _str_change($search, $replace, $start, $end) // used by Conditions
{
$this->CI->unit->run($search, 'is_string', 'Testing input "search" of _str_change function');
      $this->CI->unit->run($replace, 'is_array', 'Testing input "replace" of _str_change function');
      $this->CI->unit->run($start, 'is_numeric', 'Testing input "start" of _str_change function');
      $this->CI->unit->run($end, 'is_numeric', 'Testing input "end" of _str_change function');
         
$before = substr($search, 0, $start);
$after = substr($search, $end);

return $before . $replace . $after;
}


/**
*
* Zistí či je podmienka pravdivá
*
* */

private function _statement($string)       // used by Conditions
{
$this->CI->unit->run($string, 'is_string', 'Testing input "string" of _statement function');

preg_match_all('#+#', $string, $array );

foreach ($array as $value)
{
   if ($value !== 'AND' && $value !== '&&' && $value !== 'OR' && $value !== '||')
   {
    $string = str_replace($value ,'( ! empty($this->conditions["' . $value . '"])? $this->conditions["' . $value . '"] : FALSE )', $string);
   }
}

if (!@eval('$return = ('. $string .');'))
{
   $this->_debug(9, $string);
}

return $return;
}
}
// END Parser Class
/* End of file Parser.php */
/* Location: ./system/libraries/Parser.php */
?>

使用方法:

<!-- IF admin -->
   Hi admin!
<!-- ELSEIF vip -->
   Welcome back member!
<!-- ELSE -->
   I don't know you ... sorry ...
<!-- END -->


希望对想用模板解析类的朋友有用,也希望有高手能有更好的扩展模板解析类的代码共享出来,能增加缓存和模板编译最好了:lol

vistai 发表于 2011-5-15 21:24:09

这个比较基本的东西。 ci官方为什么不加上去呢。。。
页: [1]
查看完整版本: 给CI模板解析类Parser增加if逻辑判断功能