3 * A generic template engine
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, this is free software
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class BaseTemplateEngine extends BaseFrameworkSystem {
26 * The local path name where all templates and sub folders for special
27 * templates are stored. We will internally determine the language plus
28 * "html" for web templates or "emails" for email templates
30 private $basePath = "";
35 private $templateType = "html";
38 * The extension for web and email templates (not compiled templates)
40 private $templateExtension = ".tpl";
43 * The extension for code templates (not compiled templates)
45 private $codeExtension = ".ctp";
48 * Path relative to $basePath and language code for compiled code-templates
50 private $compileOutputPath = "templates/_compiled";
53 * The raw (maybe uncompiled) template
55 private $rawTemplateData = "";
58 * Template data with compiled-in variables
60 private $compiledData = "";
63 * The last loaded template's FQFN for debugging the engine
65 private $lastTemplate = "";
68 * The variable stack for the templates
70 private $varStack = array();
73 * Configuration variables in a simple array
75 private $configVariables = array();
78 * Loaded templates for recursive protection and detection
80 private $loadedTemplates = array();
83 * Compiled templates for recursive protection and detection
85 private $compiledTemplates = array();
88 * Loaded raw template data
90 private $loadedRawData = null;
93 * Raw templates which are linked in code templates
95 private $rawTemplates = null;
98 * A regular expression for variable=value pairs
100 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
103 * A regular expression for filtering out code tags
105 * E.g.: {?template:variable=value;var2=value2;[...]?}
107 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
112 private $helpers = array();
115 * Current variable group
117 private $currGroup = 'general';
120 * All template groups except "general"
122 private $varGroups = array();
124 // Exception codes for the template engine
125 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
126 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
127 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
130 * Protected constructor
132 * @param $className Name of the class
135 protected function __construct ($className) {
136 // Call parent constructor
137 parent::__construct($className);
140 $this->removeNumberFormaters();
141 $this->removeSystemArray();
145 * Search for a variable in the stack
147 * @param $var The variable we are looking for
148 * @return $idx FALSE means not found, >=0 means found on a specific index
150 private function isVariableAlreadySet ($var) {
151 // First everything is not found
154 // Is the group there?
155 if (isset($this->varStack[$this->currGroup])) {
157 foreach ($this->varStack[$this->currGroup] as $idx=>$currEntry) {
158 // Is the entry found?
159 if ($currEntry['name'] == $var) {
167 // Return the current position
172 * Return a content of a variable or null if not found
174 * @param $var The variable we are looking for
175 * @return $content Content of the variable or null if not found
177 private function readVariable ($var) {
178 // First everything is not found
181 // Get variable index
182 $found = $this->isVariableAlreadySet($var);
184 // Is the variable found?
185 if ($found !== false) {
187 $found = $this->varStack[$this->currGroup][$found]['value'];
190 //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.",var=".$var.", found=".$found."<br />\n";
192 // Return the current position
197 * Add a variable to the stack
199 * @param $var The variable we are looking for
200 * @param $value The value we want to store in the variable
203 private function addVariable ($var, $value) {
204 // Set general variable group
205 $this->setVariableGroup('general');
207 // Add it to the stack
208 $this->addGroupVariable($var, $value);
212 * Returns all variables of current group or empty array
214 * @return $result Wether array of found variables or empty array
216 private function readCurrentGroup () {
217 // Default is not found
220 // Is the group there?
221 if (isset($this->varStack[$this->currGroup])) {
223 $result = $this->varStack[$this->currGroup];
231 * Settter for variable group
233 * @param $groupName Name of variable group
234 * @param $add Wether add this group
237 public function setVariableGroup ($groupName, $add = true) {
239 //* DEBIG: */ echo __METHOD__.": currGroup=".$groupName."<br />\n";
240 $this->currGroup = $groupName;
242 // Skip group 'general'
243 if (($groupName != 'general') && ($add === true)) {
244 $this->varGroups[$groupName] = 'OK';
250 * Adds a variable to current group
252 * @param $var Variable to set
253 * @param $value Value to store in variable
256 public function addGroupVariable ($var, $value) {
257 //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.", var=".$var.", value=".$value."<br />\n";
259 // Get current variables in group
260 $currVars = $this->readCurrentGroup();
262 // Append our variable
268 // Add it to the stack
269 $this->varStack[$this->currGroup] = $currVars;
273 * Modify an entry on the stack
275 * @param $var The variable we are looking for
276 * @param $value The value we want to store in the variable
279 private function modifyVariable ($var, $value) {
280 // Get index for variable
281 $idx = $this->isVariableAlreadySet($var);
283 // Is the variable set?
284 if ($idx !== false) {
286 $this->varStack[$this->currGroup][$idx]['value'] = $value;
291 * Setter for template type. Only "html", "emails" and "compiled" should
294 * @param $templateType The current template's type
297 private final function setTemplateType ($templateType) {
298 $this->templateType = (string) $templateType;
302 * Setter for the last loaded template's FQFN
304 * @param $template The last loaded template
307 private final function setLastTemplate ($template) {
308 $this->lastTemplate = (string) $template;
312 * Getter for the last loaded template's FQFN
314 * @return $template The last loaded template
316 private final function getLastTemplate () {
317 return $this->lastTemplate;
321 * Setter for base path
323 * @param $basePath The local base path for all templates
326 public final function setBasePath ($basePath) {
328 $this->basePath = (string) $basePath;
332 * Getter for base path
334 * @return $basePath The local base path for all templates
336 public final function getBasePath () {
338 return $this->basePath;
342 * Setter for template extension
344 * @param $templateExtension The file extension for all uncompiled
348 public final function setRawTemplateExtension ($templateExtension) {
350 $this->templateExtension = (string) $templateExtension;
354 * Setter for code template extension
356 * @param $codeExtension The file extension for all uncompiled
360 public final function setCodeTemplateExtension ($codeExtension) {
362 $this->codeExtension = (string) $codeExtension;
366 * Getter for template extension
368 * @return $templateExtension The file extension for all uncompiled
371 public final function getRawTemplateExtension () {
373 return $this->templateExtension;
377 * Getter for code-template extension
379 * @return $codeExtension The file extension for all code-
382 public final function getCodeTemplateExtension () {
384 return $this->codeExtension;
388 * Setter for path of compiled templates
390 * @param $compileOutputPath The local base path for all compiled
394 public final function setCompileOutputPath ($compileOutputPath) {
396 $this->compileOutputPath = (string) $compileOutputPath;
400 * Getter for template type
402 * @return $templateType The current template's type
404 public final function getTemplateType () {
405 return $this->templateType;
409 * Assign (add) a given variable with a value
411 * @param $var The variable we are looking for
412 * @param $value The value we want to store in the variable
414 * @throws EmptyVariableException If the variable name is left empty
416 public final function assignVariable ($var, $value) {
417 // Trim spaces of variable name
420 // Empty variable found?
422 // Throw an exception
423 throw new EmptyVariableException(array($this, 'var'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
426 // First search for the variable if it was already added
427 $idx = $this->isVariableAlreadySet($var);
430 if ($idx === false) {
431 // Add it to the stack
432 //* DEBUG: */ echo "ADD: ".$var."<br />\n";
433 $this->addVariable($var, $value);
434 } elseif (!empty($value)) {
435 // Modify the stack entry
436 //* DEBUG: */ echo "MOD: ".$var."<br />\n";
437 $this->modifyVariable($var, $value);
442 * Removes a given variable
444 * @param $var The variable we are looking for
447 public final function removeVariable ($var) {
448 // First search for the variable if it was already added
449 $idx = $this->isVariableAlreadySet($var);
452 if ($idx !== false) {
453 // Remove this variable
454 $this->varStack->offsetUnset($idx);
459 * Private setter for raw template data
461 * @param $rawTemplateData The raw data from the template
464 private final function setRawTemplateData ($rawTemplateData) {
465 // And store it in this class
466 //* DEBUG: */ echo __METHOD__.":".$this->getUniqueId().": ".strlen($rawTemplateData)." Bytes set.<br />\n";
467 //* DEBUG: */ echo $this->currGroup." variables: ".count($this->varStack[$this->currGroup]).", groups=".count($this->varStack)."<br />\n";
468 $this->rawTemplateData = (string) $rawTemplateData;
472 * Getter for raw template data
474 * @return $rawTemplateData The raw data from the template
476 public final function getRawTemplateData () {
477 //* DEBUG: */ echo __METHOD__.":".$this->getUniqueId().": ".strlen($this->rawTemplateData)." Bytes read.<br />\n";
478 return $this->rawTemplateData;
482 * Private setter for compiled templates
486 private final function setCompiledData ($compiledData) {
487 // And store it in this class
488 //* DEBUG: */ echo __METHOD__.":".$this->getUniqueId().": ".strlen($compiledData)." Bytes set.<br />\n";
489 $this->compiledData = (string) $compiledData;
493 * Getter for compiled templates
495 public final function getCompiledData () {
496 //* DEBUG: */ echo __METHOD__.":".$this->getUniqueId().": ".strlen($this->compiledData)." Bytes read.<br />\n";
497 return $this->compiledData;
501 * Private loader for all template types
503 * @param $template The template we shall load
506 private function loadTemplate ($template) {
507 // Get extension for the template
508 $ext = $this->getRawTemplateExtension();
510 // If we shall load a code-template we need to switch the file extension
511 if ($this->getTemplateType() == $this->getConfigInstance()->readConfig('code_template_type')) {
512 // Switch over to the code-template extension
513 $ext = $this->getCodeTemplateExtension();
516 // Construct the FQFN for the template by honoring the current language
517 $fqfn = sprintf("%s%s/%s/%s%s",
518 $this->getBasePath(),
519 $this->getLanguageInstance()->getLanguageCode(),
520 $this->getTemplateType(),
525 // Load the raw template data
526 $this->loadRawTemplateData($fqfn);
530 * A private loader for raw template names
532 * @param $fqfn The full-qualified file name for a template
535 private function loadRawTemplateData ($fqfn) {
536 // Get a input/output instance from the middleware
537 $ioInstance = $this->getFileIoInstance();
539 // Some debug code to look on the file which is being loaded
540 //* DEBUG: */ echo __METHOD__.": FQFN=".$fqfn."<br />\n";
542 // Load the raw template
543 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
545 // Store the template's contents into this class
546 $this->setRawTemplateData($rawTemplateData);
548 // Remember the template's FQFN
549 $this->setLastTemplate($fqfn);
553 * Try to assign an extracted template variable as a "content" or 'config'
556 * @param $varName The variable's name (shall be content orconfig) by
558 * @param $var The variable we want to assign
560 private function assignTemplateVariable ($varName, $var) {
561 // Is it not a config variable?
562 if ($varName != 'config') {
563 // Regular template variables
564 $this->assignVariable($var, "");
566 // Configuration variables
567 $this->assignConfigVariable($var);
572 * Extract variables from a given raw data stream
574 * @param $rawData The raw template data we shall analyze
577 private function extractVariablesFromRawData ($rawData) {
579 $rawData = (string) $rawData;
581 // Search for variables
582 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
584 // Did we find some variables?
585 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
586 // Initialize all missing variables
587 foreach ($variableMatches[3] as $key=>$var) {
589 $varName = $variableMatches[1][$key];
591 // Workarround: Do not assign empty variables
593 // Try to assign it, empty strings are being ignored
594 $this->assignTemplateVariable($varName, $var);
601 * Main analysis of the loaded template
603 * @param $templateMatches Found template place-holders, see below
606 *---------------------------------
607 * Structure of $templateMatches:
608 *---------------------------------
609 * [0] => Array - An array with all full matches
610 * [1] => Array - An array with left part (before the ":") of a match
611 * [2] => Array - An array with right part of a match including ":"
612 * [3] => Array - An array with right part of a match excluding ":"
614 private function analyzeTemplate (array $templateMatches) {
615 // Backup raw template data
616 $backup = $this->getRawTemplateData();
618 // Initialize some arrays
619 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
621 // Load all requested templates
622 foreach ($templateMatches[1] as $template) {
624 // Load and compile only templates which we have not yet loaded
625 // RECURSIVE PROTECTION! BE CAREFUL HERE!
626 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
628 // Template not found, but maybe variable assigned?
629 if ($this->isVariableAlreadySet($template) !== false) {
630 // Use that content here
631 $this->loadedRawData[$template] = $this->readVariable($template);
633 // Recursive protection:
634 $this->loadedTemplates[] = $template;
636 // Then try to search for code-templates
638 // Load the code template and remember it's contents
639 $this->loadCodeTemplate($template);
640 $this->loadedRawData[$template] = $this->getRawTemplateData();
642 // Remember this template for recursion detection
643 // RECURSIVE PROTECTION!
644 $this->loadedTemplates[] = $template;
645 } catch (FileNotFoundException $e) {
646 // Even this is not done... :/
647 $this->rawTemplates[] = $template;
648 } catch (FilePointerNotOpenedException $e) {
649 // Even this is not done... :/
650 $this->rawTemplates[] = $template;
656 // Restore the raw template data
657 $this->setRawTemplateData($backup);
661 * Compile a given raw template code and remember it for later usage
663 * @param $code The raw template code
664 * @param $template The template's name
667 private function compileCode ($code, $template) {
668 // Is this template already compiled?
669 if (in_array($template, $this->compiledTemplates)) {
674 // Remember this template being compiled
675 $this->compiledTemplates[] = $template;
677 // Compile the loaded code in five steps:
679 // 1. Backup current template data
680 $backup = $this->getRawTemplateData();
682 // 2. Set the current template's raw data as the new content
683 $this->setRawTemplateData($code);
685 // 3. Compile the template data
686 $this->compileTemplate();
688 // 4. Remember it's contents
689 $this->loadedRawData[$template] = $this->getRawTemplateData();
691 // 5. Restore the previous raw content from backup variable
692 $this->setRawTemplateData($backup);
696 * Insert all given and loaded templates by running through all loaded
697 * codes and searching for their place-holder in the main template
699 * @param $templateMatches See method analyzeTemplate()
702 private function insertAllTemplates (array $templateMatches) {
703 // Run through all loaded codes
704 foreach ($this->loadedRawData as $template=>$code) {
706 // Search for the template
707 $foundIndex = array_search($template, $templateMatches[1]);
709 // Lookup the matching template replacement
710 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
712 // Get the current raw template
713 $rawData = $this->getRawTemplateData();
715 // Replace the space holder with the template code
716 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
718 // Set the new raw data
719 $this->setRawTemplateData($rawData);
725 * Load all extra raw templates
729 private function loadExtraRawTemplates () {
730 // Are there some raw templates we need to load?
731 if (count($this->rawTemplates) > 0) {
732 // Try to load all raw templates
733 foreach ($this->rawTemplates as $key => $template) {
736 $this->loadWebTemplate($template);
738 // Remember it's contents
739 $this->rawTemplates[$template] = $this->getRawTemplateData();
741 // Remove it from the loader list
742 unset($this->rawTemplates[$key]);
744 // Remember this template for recursion detection
745 // RECURSIVE PROTECTION!
746 $this->loadedTemplates[] = $template;
747 } catch (FileNotFoundException $e) {
748 // This template was never found. We silently ignore it
749 unset($this->rawTemplates[$key]);
750 } catch (FilePointerNotOpenedException $e) {
751 // This template was never found. We silently ignore it
752 unset($this->rawTemplates[$key]);
759 * Assign all found template variables
761 * @param $varMatches An array full of variable/value pairs.
763 * @todo Unfinished work or don't die here.
765 private function assignAllVariables (array $varMatches) {
766 // Search for all variables
767 foreach ($varMatches[1] as $key=>$var) {
769 // Detect leading equals
770 if (substr($varMatches[2][$key], 0, 1) == "=") {
771 // Remove and cast it
772 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
775 // Do we have some quotes left and right side? Then it is free text
776 if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
777 // Free string detected! Which we can assign directly
778 $this->assignVariable($var, $varMatches[3][$key]);
779 } elseif (!empty($varMatches[2][$key])) {
780 // Non-string found so we need some deeper analysis...
781 die("Deeper analysis not yet implemented!");
784 } // for ($varMatches ...
787 * Compiles all loaded raw templates
789 * @param $templateMatches See method analyzeTemplate() for details
792 private function compileRawTemplateData (array $templateMatches) {
793 // Are some code-templates found which we need to compile?
794 if (count($this->loadedRawData) > 0) {
797 foreach ($this->loadedRawData as $template=>$code) {
799 // Is this template already compiled?
800 if (in_array($template, $this->compiledTemplates)) {
805 // Search for the template
806 $foundIndex = array_search($template, $templateMatches[1]);
808 // Lookup the matching variable data
809 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
811 // Split it up with another reg. exp. into variable=value pairs
812 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
814 // Assign all variables
815 $this->assignAllVariables($varMatches);
817 } // END - if (isset($templateMatches ...
819 // Compile the loaded template
820 $this->compileCode($code, $template);
822 } // END - foreach ($this->loadedRawData ...
824 // Insert all templates
825 $this->insertAllTemplates($templateMatches);
827 } // END - if (count($this->loadedRawData) ...
831 * Inserts all raw templates into their respective variables
835 private function insertRawTemplates () {
836 // Load all templates
837 foreach ($this->rawTemplates as $template=>$content) {
838 // Set the template as a variable with the content
839 $this->assignVariable($template, $content);
844 * Finalizes the compilation of all template variables
848 private function finalizeVariableCompilation () {
850 $content = $this->getRawTemplateData();
851 //* DEBUG: */ echo __METHOD__.": content before=".strlen($content)." (".md5($content).")<br />\n";
853 // Walk through all variables
854 foreach ($this->varStack['general'] as $currEntry) {
855 //* DEBUG: */ echo __METHOD__.": name=".$currEntry['name'].", value=<pre>".htmlentities($currEntry['value'])."</pre>\n";
856 // Replace all [$var] or {?$var?} with the content
857 // Old behaviour, will become obsolete!
858 $content = str_replace("\$content[".$currEntry['name']."]", $currEntry['value'], $content);
860 // Yet another old way
861 $content = str_replace("[".$currEntry['name']."]", $currEntry['value'], $content);
864 $content = str_replace("{?".$currEntry['name']."?}", $currEntry['value'], $content);
867 //* DEBUG: */ echo __METHOD__.": content after=".strlen($content)." (".md5($content).")<br />\n";
869 // Set the content back
870 $this->setRawTemplateData($content);
874 * Load a specified web template into the engine
876 * @param $template The web template we shall load which is located in
880 public function loadWebTemplate ($template) {
882 $this->setTemplateType($this->getConfigInstance()->readConfig('web_template_type'));
884 // Load the special template
885 $this->loadTemplate($template);
889 * Assign a given congfiguration variable with a value
891 * @param $var The configuration variable we want to assign
894 public function assignConfigVariable ($var) {
895 // Sweet and simple...
896 $this->configVariables[$var] = $this->getConfigInstance()->readConfig($var);
900 * Load a specified email template into the engine
902 * @param $template The email template we shall load which is located in
903 * "emails" by default
906 public function loadEmailTemplate ($template) {
908 $this->setTemplateType($this->getConfigInstance()->readConfig('email_template_type'));
910 // Load the special template
911 $this->loadTemplate($template);
915 * Load a specified code template into the engine
917 * @param $template The code template we shall load which is
918 * located in "code" by default
921 public function loadCodeTemplate ($template) {
923 $this->setTemplateType($this->getConfigInstance()->readConfig('code_template_type'));
925 // Load the special template
926 $this->loadTemplate($template);
930 * Compile all variables by inserting their respective values
933 * @todo Make this code some nicer...
935 public final function compileVariables () {
936 // Initialize the $content array
937 $validVar = $this->getConfigInstance()->readConfig('tpl_valid_var');
940 // Iterate through all general variables
941 foreach ($this->varStack['general'] as $currVariable) {
942 // Transfer it's name/value combination to the $content array
943 //* DEBUG: */ echo $currVariable['name']."=<pre>".htmlentities($currVariable['value'])."</pre>\n";
944 $dummy[$currVariable['name']] = $currVariable['value'];
948 // Set the new variable (don't remove the second dollar !)
951 // Prepare all configuration variables
952 $config = $this->configVariables;
954 // Remove some variables
956 unset($currVariable);
958 // Run the compilation twice to get content from helper classes in
961 // Finalize the compilation of template variables
962 $this->finalizeVariableCompilation();
964 // Prepare the eval() command for comiling the template
965 $eval = sprintf("\$result = \"%s\";",
966 addslashes($this->getRawTemplateData())
969 // This loop does remove the backslashes (\) in PHP parameters
970 while (strpos($eval, "<?") !== false) {
971 // Get left part before "<?"
972 $evalLeft = substr($eval, 0, strpos($eval, "<?"));
974 // Get all from right of "<?"
975 $evalRight = substr($eval, (strpos($eval, "<?") + 2));
977 // Is this a full PHP tag?
978 if (substr(strtolower($evalRight), 0, 3) == "php") {
979 // Remove "php" string from full PHP tag
980 $evalRight = substr($evalRight, 3);
983 // Cut middle part out and remove escapes
984 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, "?>")));
985 $evalMiddle = stripslashes($evalMiddle);
987 // Remove the middle part from right one
988 $evalRight = substr($evalRight, (strpos($evalRight, "?>") + 2));
990 // And put all together
991 $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
994 // Prepare PHP code for eval() command
998 "%>", "\n\$result .= \"", $eval
1002 // Run the constructed command. This will "compile" all variables in
1005 // Goes something wrong?
1006 if (!isset($result)) {
1007 // Output eval command
1008 $this->debugOutput(sprintf("Failed eval() code: <pre>%s</pre>", $this->markupCode($eval, true)), true);
1010 // Output backtrace here
1011 $this->debugBackTrace();
1014 // Set raw template data
1015 $this->setRawTemplateData($result);
1019 // Final variable assignment
1020 $this->finalizeVariableCompilation();
1022 // Set the new content
1023 $this->setCompiledData($this->getRawTemplateData());
1027 * Compile all required templates into the current loaded one
1030 * @throws UnexpectedTemplateTypeException If the template type is
1032 * @throws InvalidArrayCountException If an unexpected array
1033 * count has been found
1035 public function compileTemplate () {
1036 // We will only work with template type "code" from configuration
1037 if ($this->getTemplateType() != $this->getConfigInstance()->readConfig('code_template_type')) {
1039 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->readConfig('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1042 // Get the raw data.
1043 $rawData = $this->getRawTemplateData();
1045 // Remove double spaces and trim leading/trailing spaces
1046 $rawData = trim(str_replace(" ", " ", $rawData));
1048 // Search for raw variables
1049 $this->extractVariablesFromRawData($rawData);
1051 // Search for code-tags which are {? ?}
1052 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1054 // Analyze the matches array
1055 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1056 // Entries are found:
1058 // The main analysis
1059 $this->analyzeTemplate($templateMatches);
1061 // Compile raw template data
1062 $this->compileRawTemplateData($templateMatches);
1064 // Are there some raw templates left for loading?
1065 $this->loadExtraRawTemplates();
1067 // Are some raw templates found and loaded?
1068 if (count($this->rawTemplates) > 0) {
1070 // Insert all raw templates
1071 $this->insertRawTemplates();
1073 // Remove the raw template content as well
1074 $this->setRawTemplateData("");
1078 } // END - if($templateMatches ...
1082 * A old deprecated method
1086 * @see BaseTemplateEngine::transferToResponse
1088 public function output () {
1089 // Check which type of template we have
1090 switch ($this->getTemplateType()) {
1091 case "html": // Raw HTML templates can be send to the output buffer
1093 $this->getWebOutputInstance()->output($this->getCompiledData());
1096 default: // Unknown type found
1097 // Construct message
1098 $msg = sprintf("[%s->%s] Unknown/unsupported template type <strong>%s</strong> detected.",
1099 $this->__toString(),
1101 $this->getTemplateType()
1104 // Write the problem to the world...
1105 $this->debugOutput($msg);
1111 * Loads a given view helper (by name)
1113 * @param $helperName The helper's name
1115 * @throws ViewHelperNotFoundException If the given view helper was not found
1117 protected function loadViewHelper ($helperName) {
1118 // Make first character upper case, rest low
1119 $helperName = ucfirst($helperName);
1121 // Is this view helper loaded?
1122 if (!isset($this->helpers[$helperName])) {
1123 // Create a class name
1124 $className = "{$helperName}ViewHelper";
1126 // Does this class exists?
1127 if (!class_exists($className)) {
1129 throw new ViewHelperNotFoundException(array($this, $helperName), self::EXCEPTION_INVALID_VIEW_HELPER);
1132 // Generate new instance
1133 $eval = sprintf("\$this->helpers[%s] = %s::create%s();",
1143 // Return the requested instance
1144 return $this->helpers[$helperName];
1148 * Assigns the last loaded raw template content with a given variable
1150 * @param $templateName Name of the template we want to assign
1151 * @param $variableName Name of the variable we want to assign
1154 public function assignTemplateWithVariable ($templateName, $variableName) {
1155 // Get the content from last loaded raw template
1156 $content = $this->getRawTemplateData();
1158 // Assign the variable
1159 $this->assignVariable($variableName, $content);
1161 // Purge raw content
1162 $this->setRawTemplateData("");
1166 * Transfers the content of this template engine to a given response instance
1168 * @param $responseInstance An instance of a response class
1171 public function transferToResponse (Responseable $responseInstance) {
1172 // Get the content and set it in the response class
1173 $responseInstance->writeToBody($this->getCompiledData());
1177 * Assigns all the application data with template variables
1179 * @param $appInstance A manageable application instance
1182 public function assignApplicationData (ManageableApplication $appInstance) {
1183 // Get long name and assign it
1184 $this->assignVariable('app_full_name' , $appInstance->getAppName());
1186 // Get short name and assign it
1187 $this->assignVariable('app_short_name', $appInstance->getAppShortName());
1189 // Get version number and assign it
1190 $this->assignVariable('app_version' , $appInstance->getAppVersion());
1194 * "Compiles" a variable by replacing {?var?} with it's content
1196 * @param $rawCode Raw code to compile
1197 * @return $rawCode Compile code with inserted variable value
1199 public function compileRawCode ($rawCode) {
1200 // Find the variables
1201 //* DEBUG: */ echo "rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
1202 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1204 // Compile all variables
1205 //* DEBUG: */ echo "<pre>".print_r($varMatches, true)."</pre>";
1206 foreach ($varMatches[0] as $match) {
1207 // Add variable tags around it
1208 $varCode = "{?".$match."?}";
1210 // Is the variable found in code? (safes some calls)
1211 if (strpos($rawCode, $varCode) !== false) {
1212 // Replace the variable with it's value, if found
1213 //* DEBUG: */ echo __METHOD__.": match=".$match."<br />\n";
1214 $rawCode = str_replace($varCode, $this->readVariable($match), $rawCode);
1218 // Return the compiled data
1223 * Getter for variable group array
1225 * @return $vargroups All variable groups
1227 public final function getVariableGroups () {
1228 return $this->varGroups;
1232 * Renames a variable in code and in stack
1234 * @param $oldName Old name of variable
1235 * @param $newName New name of variable
1238 public function renameVariable ($oldName, $newName) {
1239 //* DEBUG: */ echo __METHOD__.": oldName={$oldName}, newName={$newName}<br />\n";
1240 // Get raw template code
1241 $rawData = $this->getRawTemplateData();
1244 $rawData = str_replace($oldName, $newName, $rawData);
1246 // Set the code back
1247 $this->setRawTemplateData($rawData);