Location: PHPKode > projects > ExTemplates Library > extemplates-library/TemplateBuilder.php
<?

/*
This script is a part of the ExTemplates Library
Author: Alexander Netkachev

Check the license.txt for copyright and terms.
*/


class TemplateBuilder {
  
  function & buildTemplateFromString($str) {
    $out = preg_split('/({[\w\d]+}|<!-- (?:BEGIN|END)(?: [\w\d]+)? [\w\d]+ -->)/',
      $str, -1, PREG_SPLIT_DELIM_CAPTURE);
    $result = $this->buildOM(&$out, 0, '');
    return new ExTemplate(&$result[1]);
  }

  function buildOM(&$a, $pos, $fullBlockName) {
    $blockArray = array();
    $arrSize = count($a);
    $blockEndsAt = $pos;
    $endName = '';
    for ($i = $pos; $i < $arrSize && $blockEndsAt == $pos; $i++) {
      $element = $a[$i];
      if ($i % 2 == 1) {
        switch (substr($element, 0, 1)) {
          case '{':
            $blockArray[trim($element, '{}')] = '';
            break;
          case '<': 
            if (substr($element, 0, 6) == '<!-- B') {
              $blockName = '';
              $className = 'TemplateBlock';
              $fullName = substr($element, 11, strlen($element) - 15);
              $parsedName = explode(' ', $fullName);
              if (count($parsedName) == 1)
                $blockName = $parsedName[0];
              else if (count($parsedName) == 2) {
                $className = $parsedName[0];
                $blockName = $parsedName[1];
              }
              $r = $this->buildOM(&$a, $i+1, $fullName);
              $i = $r[0];
              if (!class_exists($className)) {
                print('Warning: TemplateBuilder->buildOM(): Class "' . $className . '" is not defined. ' .
                  'The "TemplateBlock" class is used instead the "' . $className . '".');
                $className = 'TemplateBlock';
              }
              $blockArray[$blockName] = new $className(&$r[1], $blockName);
            } else {
              $endName = substr($element, 9, strlen($element) - 13);
              $blockEndsAt = $i;
            }
            break;
        }
      } else
        if (strlen($element) > 0)
          $blockArray[] = $element;
    }
    if ($fullBlockName != $endName) 
      exit ('Inconsistent template. Please check the pair of the "' . $fullBlockName . '" block.');
    return array($blockEndsAt, &$blockArray);
  }
}

?>
Return current item: ExTemplates Library