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. This must be initialized and
69 * shall become an instance of FrameworkArrayObject.
71 private $varStack = null;
74 * Configuration variables in a simple array
76 private $configVariables = array();
79 * Loaded templates for recursive protection and detection
81 private $loadedTemplates = array();
84 * Compiled templates for recursive protection and detection
86 private $compiledTemplates = array();
89 * Loaded raw template data
91 private $loadedRawData = null;
94 * Raw templates which are linked in code templates
96 private $rawTemplates = null;
99 * A regular expression for variable=value pairs
101 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
104 * A regular expression for filtering out code tags
106 * E.g.: {?template:variable=value;var2=value2;[...]?}
108 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
113 private $helpers = array();
115 // Exception codes for the template engine
116 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x020;
117 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x021;
118 const EXCEPTION_INVALID_VIEW_HELPER = 0x022;
121 * Initialize the variable stack. This holds all variables for later
126 public final function initVariableStack () {
127 $this->varStack = new FrameworkArrayObject("FakedVariableStack");
131 * Protected constructor
133 * @param $className Name of the class
136 protected function __construct ($className) {
137 // Call parent constructor
138 parent::__construct($className);
141 $this->removeNumberFormaters();
142 $this->removeSystemArray();
146 * Search for a variable in the stack
148 * @param $var The variable we are looking for
149 * @return $idx FALSE means not found, >=0 means found on a specific index
151 private function isVariableAlreadySet ($var) {
152 // First everything is not found
156 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
158 $currEntry = $idx->current();
160 // Is the entry found?
161 if ($currEntry['name'] == $var) {
163 $found = $idx->key();
168 // Return the current position
173 * Return a content of a variable or null if not found
175 * @param $var The variable we are looking for
176 * @return $content Content of the variable or null if not found
178 private function readVariable ($var) {
179 // First everything is not found
183 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
185 $currEntry = $idx->current();
187 // Is the entry found?
188 if ($currEntry['name'] == $var) {
190 $content = $currEntry['value'];
195 // Return the current position
200 * Add a variable to the stack
202 * @param $var The variable we are looking for
203 * @param $value The value we want to store in the variable
206 private function addVariable ($var, $value) {
207 // Add it to the stack
208 $this->varStack->append(array(
209 'name' => trim($var),
210 'value' => trim($value)
215 * Modify an entry on the stack
217 * @param $var The variable we are looking for
218 * @param $value The value we want to store in the variable
221 private function modifyVariable ($var, $value) {
222 // It should be there so let's look again...
223 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
225 $currEntry = $idx->current();
227 // Is this the requested variable?
228 if ($currEntry['name'] == $var) {
229 // Change it to the other value
230 $this->varStack->offsetSet($idx->key(), array(
239 * Setter for template type. Only "html", "emails" and "compiled" should
242 * @param $templateType The current template's type
245 private final function setTemplateType ($templateType) {
247 $templateType = (string) $templateType;
249 // And set it (only 2 letters)
250 $this->templateType = $templateType;
254 * Setter for the last loaded template's FQFN
256 * @param $template The last loaded template
259 private final function setLastTemplate ($template) {
261 $template = (string) $template;
262 $this->lastTemplate = $template;
266 * Getter for the last loaded template's FQFN
268 * @return $template The last loaded template
270 private final function getLastTemplate () {
271 return $this->lastTemplate;
275 * Setter for base path
277 * @param $basePath The local base path for all templates
280 public final function setBasePath ($basePath) {
282 $basePath = (string) $basePath;
285 $this->basePath = $basePath;
289 * Getter for base path
291 * @return $basePath The local base path for all templates
293 public final function getBasePath () {
295 return $this->basePath;
299 * Setter for template extension
301 * @param $templateExtension The file extension for all uncompiled
305 public final function setRawTemplateExtension ($templateExtension) {
307 $templateExtension = (string) $templateExtension;
310 $this->templateExtension = $templateExtension;
314 * Setter for code template extension
316 * @param $codeExtension The file extension for all uncompiled
320 public final function setCodeTemplateExtension ($codeExtension) {
322 $codeExtension = (string) $codeExtension;
325 $this->codeExtension = $codeExtension;
329 * Getter for template extension
331 * @return $templateExtension The file extension for all uncompiled
334 public final function getRawTemplateExtension () {
336 return $this->templateExtension;
340 * Getter for code-template extension
342 * @return $codeExtension The file extension for all code-
345 public final function getCodeTemplateExtension () {
347 return $this->codeExtension;
351 * Setter for path of compiled templates
353 * @param $compileOutputPath The local base path for all compiled
357 public final function setCompileOutputPath ($compileOutputPath) {
359 $compileOutputPath = (string) $compileOutputPath;
362 $this->compileOutputPath = $compileOutputPath;
366 * Getter for template type
368 * @return $templateType The current template's type
370 public final function getTemplateType () {
371 return $this->templateType;
375 * Assign (add) a given variable with a value
377 * @param $var The variable we are looking for
378 * @param $value The value we want to store in the variable
381 public final function assignVariable ($var, $value) {
382 // First search for the variable if it was already added
383 $idx = $this->isVariableAlreadySet($var);
386 if ($idx === false) {
387 // Add it to the stack
388 $this->addVariable($var, $value);
389 } elseif (!empty($value)) {
390 // Modify the stack entry
391 $this->modifyVariable($var, $value);
396 * Removes a given variable
398 * @param $var The variable we are looking for
401 public final function removeVariable ($var) {
402 // First search for the variable if it was already added
403 $idx = $this->isVariableAlreadySet($var);
406 if ($idx !== false) {
407 // Remove this variable
408 $this->varStack->offsetUnset($idx);
413 * Private setter for raw template data
415 * @param $rawTemplateData The raw data from the template
418 private final function setRawTemplateData ($rawTemplateData) {
420 $rawTemplateData = (string) $rawTemplateData;
422 // And store it in this class
423 $this->rawTemplateData = $rawTemplateData;
427 * Private setter for compiled templates
431 private final function setCompiledData ($compiledData) {
433 $compiledData = (string) $compiledData;
435 // And store it in this class
436 $this->compiledData = $compiledData;
440 * Private loader for all template types
442 * @param $template The template we shall load
445 private function loadTemplate ($template) {
447 $template = (string) $template;
449 // Get extension for the template
450 $ext = $this->getRawTemplateExtension();
452 // If we shall load a code-template we need to switch the file extension
453 if ($this->getTemplateType() == $this->getConfigInstance()->readConfig('code_template_type')) {
454 // Switch over to the code-template extension
455 $ext = $this->getCodeTemplateExtension();
458 // Construct the FQFN for the template by honoring the current language
459 $fqfn = sprintf("%s%s/%s/%s%s",
460 $this->getBasePath(),
461 $this->getLanguageInstance()->getLanguageCode(),
462 $this->getTemplateType(),
467 // Load the raw template data
468 $this->loadRawTemplateData($fqfn);
472 * A private loader for raw template names
474 * @param $fqfn The full-qualified file name for a template
476 * @throws NullPointerException If $inputInstance is null
477 * @throws NoObjectException If $inputInstance is not an object
478 * @throws MissingMethodException If $inputInstance is missing a
481 private function loadRawTemplateData ($fqfn) {
482 // Get a input/output instance from the middleware
483 $ioInstance = $this->getFileIoInstance();
485 // Validate the instance
486 if (is_null($ioInstance)) {
488 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
489 } elseif (!is_object($ioInstance)) {
490 // Throw another exception
491 throw new NoObjectException($ioInstance, self::EXCEPTION_IS_NO_OBJECT);
492 } elseif (!method_exists($ioInstance, 'loadFileContents')) {
493 // Throw yet another exception
494 throw new MissingMethodException(array($ioInstance, 'loadFileContents'), self::EXCEPTION_MISSING_METHOD);
497 /* DEBUG: */ echo __METHOD__.": FQFN=".$fqfn."<br />\n";
499 // Load the raw template
500 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
502 // Store the template's contents into this class
503 $this->setRawTemplateData($rawTemplateData);
505 // Remember the template's FQFN
506 $this->setLastTemplate($fqfn);
510 * Try to assign an extracted template variable as a "content" or "config"
513 * @param $varName The variable's name (shall be content orconfig) by
515 * @param $var The variable we want to assign
517 private function assignTemplateVariable ($varName, $var) {
518 // Is it not a config variable?
519 if ($varName != "config") {
520 // Regular template variables
521 $this->assignVariable($var, "");
523 // Configuration variables
524 $this->assignConfigVariable($var);
529 * Extract variables from a given raw data stream
531 * @param $rawData The raw template data we shall analyze
534 private function extractVariablesFromRawData ($rawData) {
536 $rawData = (string) $rawData;
538 // Search for variables
539 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
541 // Did we find some variables?
542 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
543 // Initialize all missing variables
544 foreach ($variableMatches[3] as $key=>$var) {
545 // Try to assign it, empty strings are being ignored
546 $this->assignTemplateVariable($variableMatches[1][$key], $var);
552 * Main analysis of the loaded template
554 * @param $templateMatches Found template place-holders, see below
557 *---------------------------------
558 * Structure of $templateMatches:
559 *---------------------------------
560 * [0] => Array - An array with all full matches
561 * [1] => Array - An array with left part (before the ":") of a match
562 * [2] => Array - An array with right part of a match including ":"
563 * [3] => Array - An array with right part of a match excluding ":"
565 private function analyzeTemplate (array $templateMatches) {
566 // Backup raw template data
567 $backup = $this->getRawTemplateData();
569 // Initialize some arrays
570 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
572 // Load all requested templates
573 foreach ($templateMatches[1] as $template) {
575 // Load and compile only templates which we have not yet loaded
576 // RECURSIVE PROTECTION! BE CAREFUL HERE!
577 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
579 // Template not found, but maybe variable assigned?
580 if ($this->isVariableAlreadySet($template) !== false) {
581 // Use that content here
582 $this->loadedRawData[$template] = $this->readVariable($template);
584 // Recursive protection:
585 $this->loadedTemplates[] = $template;
587 // Then try to search for code-templates
589 // Load the code template and remember it's contents
590 $this->loadCodeTemplate($template);
591 $this->loadedRawData[$template] = $this->getRawTemplateData();
593 // Remember this template for recursion detection
594 // RECURSIVE PROTECTION!
595 $this->loadedTemplates[] = $template;
596 } catch (FileNotFoundException $e) {
597 // Even this is not done... :/
598 $this->rawTemplates[] = $template;
599 } catch (FilePointerNotOpenedException $e) {
600 // Even this is not done... :/
601 $this->rawTemplates[] = $template;
607 // Restore the raw template data
608 $this->setRawTemplateData($backup);
612 * Compile a given raw template code and remember it for later usage
614 * @param $code The raw template code
615 * @param $template The template's name
618 private function compileCode ($code, $template) {
619 // Is this template already compiled?
620 if (in_array($template, $this->compiledTemplates)) {
625 // Remember this template being compiled
626 $this->compiledTemplates[] = $template;
628 // Compile the loaded code in five steps:
630 // 1. Backup current template data
631 $backup = $this->getRawTemplateData();
633 // 2. Set the current template's raw data as the new content
634 $this->setRawTemplateData($code);
636 // 3. Compile the template data
637 $this->compileTemplate();
639 // 4. Remember it's contents
640 $this->loadedRawData[$template] = $this->getRawTemplateData();
642 // 5. Restore the previous raw content from backup variable
643 $this->setRawTemplateData($backup);
647 * Insert all given and loaded templates by running through all loaded
648 * codes and searching for their place-holder in the main template
650 * @param $templateMatches See method analyzeTemplate()
653 private function insertAllTemplates (array $templateMatches) {
654 // Run through all loaded codes
655 foreach ($this->loadedRawData as $template=>$code) {
657 // Search for the template
658 $foundIndex = array_search($template, $templateMatches[1]);
660 // Lookup the matching template replacement
661 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
663 // Get the current raw template
664 $rawData = $this->getRawTemplateData();
666 // Replace the space holder with the template code
667 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
669 // Set the new raw data
670 $this->setRawTemplateData($rawData);
678 * Load all extra raw templates
682 private function loadExtraRawTemplates () {
683 // Are there some raw templates we need to load?
684 if (count($this->rawTemplates) > 0) {
685 // Try to load all raw templates
686 foreach ($this->rawTemplates as $key => $template) {
689 $this->loadWebTemplate($template);
691 // Remember it's contents
692 $this->rawTemplates[$template] = $this->getRawTemplateData();
694 // Remove it from the loader list
695 unset($this->rawTemplates[$key]);
697 // Remember this template for recursion detection
698 // RECURSIVE PROTECTION!
699 $this->loadedTemplates[] = $template;
700 } catch (FileNotFoundException $e) {
701 // This template was never found. We silently ignore it
702 unset($this->rawTemplates[$key]);
703 } catch (FilePointerNotOpenedException $e) {
704 // This template was never found. We silently ignore it
705 unset($this->rawTemplates[$key]);
712 * Assign all found template variables
714 * @param $varMatches An array full of variable/value pairs.
716 * @todo Unfinished work or don't die here.
718 private function assignAllVariables (array $varMatches) {
719 // Search for all variables
720 foreach ($varMatches[1] as $key=>$var) {
722 // Detect leading equals
723 if (substr($varMatches[2][$key], 0, 1) == "=") {
724 // Remove and cast it
725 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
728 // Do we have some quotes left and right side? Then it is free text
729 if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
730 // Free string detected! Which we can assign directly
731 $this->assignVariable($var, $varMatches[3][$key]);
732 } elseif (!empty($varMatches[2][$key])) {
733 // Non-string found so we need some deeper analysis...
734 die("Deeper analysis not yet implemented!");
737 } // for ($varMatches ...
740 * Compiles all loaded raw templates
742 * @param $templateMatches See method analyzeTemplate() for details
745 private function compileRawTemplateData (array $templateMatches) {
746 // Are some code-templates found which we need to compile?
747 if (count($this->loadedRawData) > 0) {
750 foreach ($this->loadedRawData as $template=>$code) {
752 // Is this template already compiled?
753 if (in_array($template, $this->compiledTemplates)) {
758 // Search for the template
759 $foundIndex = array_search($template, $templateMatches[1]);
761 // Lookup the matching variable data
762 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
764 // Split it up with another reg. exp. into variable=value pairs
765 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
767 // Assign all variables
768 $this->assignAllVariables($varMatches);
770 } // END - if (isset($templateMatches ...
772 // Compile the loaded template
773 $this->compileCode($code, $template);
775 } // END - foreach ($this->loadedRawData ...
777 // Insert all templates
778 $this->insertAllTemplates($templateMatches);
780 } // END - if (count($this->loadedRawData) ...
784 * Inserts all raw templates into their respective variables
788 private function insertRawTemplates () {
789 // Load all templates
790 foreach ($this->rawTemplates as $template=>$content) {
791 // Set the template as a variable with the content
792 $this->assignVariable($template, $content);
797 * Finalizes the compilation of all template variables
801 private function finalizeVariableCompilation () {
803 $content = $this->getRawTemplateData();
805 // Walk through all variables
806 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
808 $currEntry = $idx->current();
810 // Replace all [$var] or {?$var?} with the content
811 //* DEBUG: */ echo "name=".$currEntry['name'].", value=<pre>".htmlentities($currEntry['value'])."</pre>\n";
812 $content = str_replace("\$content[".$currEntry['name']."]", $currEntry['value'], $content);
813 $content = str_replace("[".$currEntry['name']."]", $currEntry['value'], $content);
814 $content = str_replace("{?".$currEntry['name']."?}", $currEntry['value'], $content);
817 // Set the content back
818 $this->setRawTemplateData($content);
822 * Getter for raw template data
824 * @return $rawTemplateData The raw data from the template
826 public final function getRawTemplateData () {
827 return $this->rawTemplateData;
831 * Getter for compiled templates
833 public final function getCompiledData () {
834 return $this->compiledData;
838 * Load a specified web template into the engine
840 * @param $template The web template we shall load which is
841 * located in "html" by default
844 public function loadWebTemplate ($template) {
846 $this->setTemplateType($this->getConfigInstance()->readConfig('web_template_type'));
848 // Load the special template
849 $this->loadTemplate($template);
853 * Assign a given congfiguration variable with a value
855 * @param $var The configuration variable we want to assign
858 public function assignConfigVariable ($var) {
859 // Sweet and simple...
860 $this->configVariables[$var] = $this->getConfigInstance()->readConfig($var);
864 * Load a specified email template into the engine
866 * @param $template The email template we shall load which is
867 * located in "emails" by default
870 public function loadEmailTemplate ($template) {
872 $this->setTemplateType($this->getConfigInstance()->readConfig('email_template_type'));
874 // Load the special template
875 $this->loadTemplate($template);
879 * Load a specified code template into the engine
881 * @param $template The code template we shall load which is
882 * located in "code" by default
885 public function loadCodeTemplate ($template) {
887 $this->setTemplateType($this->getConfigInstance()->readConfig('code_template_type'));
889 // Load the special template
890 $this->loadTemplate($template);
894 * Compile all variables by inserting their respective values
897 * @todo Make this code some nicer...
899 public final function compileVariables () {
900 // Initialize the $content array
901 $validVar = $this->getConfigInstance()->readConfig('tpl_valid_var');
904 // Iterate through all variables
905 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
907 // Get current variable from the stack
908 $currVariable = $idx->current();
910 // Transfer it's name/value combination to the $content array
911 //* DEBUG: */ echo $currVariable['name']."=<pre>".htmlentities($currVariable['value'])."</pre>\n";
912 $dummy[$currVariable['name']] = $currVariable['value'];
916 // Set the new variable (don't remove the second dollar !)
919 // Prepare all configuration variables
920 $config = $this->configVariables;
922 // Remove some variables
924 unset($currVariable);
926 // Run the compilation twice to get content from helper classes in
929 // Finalize the compilation of template variables
930 $this->finalizeVariableCompilation();
932 // Prepare the eval() command for comiling the template
933 $eval = sprintf("\$result = \"%s\";",
934 addslashes($this->getRawTemplateData())
937 // This loop does remove the backslashes (\) in PHP parameters
938 while (strpos($eval, "<?") !== false) {
939 // Get left part before "<?"
940 $evalLeft = substr($eval, 0, strpos($eval, "<?"));
942 // Get all from right of "<?"
943 $evalRight = substr($eval, (strpos($eval, "<?") + 2));
945 // Is this a full PHP tag?
946 if (substr(strtolower($evalRight), 0, 3) == "php") {
947 // Remove "php" string from full PHP tag
948 $evalRight = substr($evalRight, 3);
951 // Cut middle part out and remove escapes
952 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, "?>")));
953 $evalMiddle = stripslashes($evalMiddle);
955 // Remove the middle part from right one
956 $evalRight = substr($evalRight, (strpos($evalRight, "?>") + 2));
958 // And put all together
959 $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
962 // Prepare PHP code for eval() command
963 $evalLength = strlen($eval);
967 "%>", "\n\$result .= \"", $eval
971 // Did something change?
972 if (strlen($eval) != $eval) {
973 // Run the constructed command. This will "compile" all variables in
977 // Goes something wrong?
978 if (!isset($result)) {
979 // Output eval command
980 $this->debugOutput(sprintf("Failed eval() code: <pre>%s</pre>", $this->markupCode($eval, true)), true);
982 // Output backtrace here
983 $this->debugBacktrace();
986 // Set raw template data
987 $this->setRawTemplateData($result);
991 // Set the new content
992 $this->setCompiledData($result);
996 * Compile all required templates into the current loaded one
999 * @throws UnexpectedTemplateTypeException If the template type is
1001 * @throws InvalidArrayCountException If an unexpected array
1002 * count has been found
1004 public final function compileTemplate () {
1005 // We will only work with template type "code" from configuration
1006 if ($this->getTemplateType() != $this->getConfigInstance()->readConfig('code_template_type')) {
1008 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->readConfig('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1011 // Get the raw data.
1012 $rawData = $this->getRawTemplateData();
1014 // Remove double spaces and trim leading/trailing spaces
1015 $rawData = trim(str_replace(" ", " ", $rawData));
1017 // Search for raw variables
1018 $this->extractVariablesFromRawData($rawData);
1020 // Search for code-tags which are {? ?}
1021 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1023 // Analyze the matches array
1024 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1025 // Entries are found:
1027 // The main analysis
1028 $this->analyzeTemplate($templateMatches);
1030 // Compile raw template data
1031 $this->compileRawTemplateData($templateMatches);
1033 // Are there some raw templates left for loading?
1034 $this->loadExtraRawTemplates();
1036 // Are some raw templates found and loaded?
1037 if (count($this->rawTemplates) > 0) {
1039 // Insert all raw templates
1040 $this->insertRawTemplates();
1042 // Remove the raw template content as well
1043 $this->setRawTemplateData("");
1047 } // END - if($templateMatches ...
1051 * Output the compiled page to the outside world. In case of web templates
1052 * this would be vaild (X)HTML code. And in case of email templates this
1053 * would store a prepared email body inside the template engine.
1057 public final function output () {
1058 // Check which type of template we have
1059 switch ($this->getTemplateType()) {
1060 case "html": // Raw HTML templates can be send to the output buffer
1062 $this->getWebOutputInstance()->output($this->getCompiledData());
1065 default: // Unknown type found
1066 // Construct message
1067 $msg = sprintf("[%s->%s] Unknown/unsupported template type <strong>%s</strong> detected.",
1068 $this->__toString(),
1070 $this->getTemplateType()
1073 // Write the problem to the world...
1074 $this->debugOutput($msg);
1080 * Loads a given view helper (by name)
1082 * @param $helperName The helper's name
1084 * @throws ViewHelperNotFoundException If the given view helper was not found
1086 protected function loadViewHelper ($helperName) {
1087 // Make first character upper case, rest low
1088 $helperName = ucfirst($helperName);
1090 // Is this view helper loaded?
1091 if (!isset($this->helpers[$helperName])) {
1092 // Create a class name
1093 $className = "{$helperName}ViewHelper";
1095 // Does this class exists?
1096 if (!class_exists($className)) {
1098 throw new ViewHelperNotFoundException(array($this, $helperName), self::EXCEPTION_INVALID_VIEW_HELPER);
1101 // Generate new instance
1102 $eval = sprintf("\$this->helpers[%s] = %s::create%s();",
1112 // Return the requested instance
1113 return $this->helpers[$helperName];
1117 * Assigns the last loaded raw template content with a given variable
1119 * @param $templateName Name of the template we want to assign
1120 * @param $variableName Name of the variable we want to assign
1123 public function assignTemplateWithVariable ($templateName, $variableName) {
1124 // Get the content from last loaded raw template
1125 $content = $this->getRawTemplateData();
1127 // Assign the variable
1128 $this->assignVariable($variableName, $content);
1130 // Purge raw content
1131 $this->setRawTemplateData("");
1135 * Transfers the content of this template engine to a given response instance
1137 * @param $responseInstance An instance of a response class
1140 public function transferToResponse (Responseable $responseInstance) {
1141 // Get the content and set it in the response class
1142 $responseInstance->writeToBody($this->getCompiledData());
1146 * Assigns all the application data with template variables
1148 * @param $appInstance A manageable application instance
1151 public function assignApplicationData (ManageableApplication $appInstance) {
1152 // Get long name and assign it
1153 $this->assignVariable("app_full_name" , $appInstance->getAppName());
1155 // Get short name and assign it
1156 $this->assignVariable("app_short_name", $appInstance->getAppShortName());
1158 // Get version number and assign it
1159 $this->assignVariable("app_version" , $appInstance->getAppVersion());
1163 * "Compiles" a variable by replacing {?var?} with it's content
1165 * @param $rawCode Raw code to compile
1166 * @return $rawCode Compile code with inserted variable value
1168 protected function compileRawCode ($rawCode) {
1169 // Find the variables
1170 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1172 // Compile all variables
1173 foreach ($varMatches[0] as $match) {
1174 // Replace the variable with it's value, if found
1175 $rawCode = str_replace("{?".$match."?}", $this->readVariable($match), $rawCode);
1178 // Return the compiled data