3 * The own template engine for loading caching and sending out the web pages
6 * @author Roland Haeder <webmaster@ship-simu.org>
8 * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
9 * @license GNU GPL 3.0 or any newer version
10 * @link http://www.ship-simu.org
12 * This program is free software: you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation, either version 3 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate {
27 * The local path name where all templates and sub folders for special
28 * templates are stored. We will internally determine the language plus
29 * "html" for web templates or "emails" for email templates
31 private $basePath = "";
34 * The extension for web and email templates (not compiled templates)
36 private $templateExtension = ".tpl";
39 * The extension for code templates (not compiled templates)
41 private $codeExtension = ".ctp";
44 * Path relative to $basePath and language code for compiled code-templates
46 private $compileOutputPath = "templates/_compiled";
49 * The raw (maybe uncompiled) template
51 private $rawTemplateData = "";
54 * Template data with compiled-in variables
56 private $compiledData = "";
59 * The last loaded template's FQFN for debugging the engine
61 private $lastTemplate = "";
64 * The variable stack for the templates. This must be initialized and
65 * shall become an instance of FrameworkArrayObject.
67 private $varStack = null;
70 * Configuration variables in a simple array
72 private $configVariables = array();
75 * Loaded templates for recursive protection and detection
77 private $loadedTemplates = array();
80 * Compiled templates for recursive protection and detection
82 private $compiledTemplates = array();
85 * Loaded raw template data
87 private $loadedRawData = null;
90 * Raw templates which are linked in code templates
92 private $rawTemplates = null;
95 * A regular expression for variable=value pairs
97 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
100 * A regular expression for filtering out code tags
102 * E.g.: {?template:variable=value;var2=value2;[...]?}
104 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
109 private $helpers = array();
111 // Exception codes for the template engine
112 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x020;
113 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x021;
114 const EXCEPTION_INVALID_VIEW_HELPER = 0x022;
117 * Protected constructor
121 protected function __construct () {
122 // Call parent constructor
123 parent::__construct(__CLASS__);
126 $this->removeNumberFormaters();
127 $this->removeSystemArray();
131 * Creates an instance of the class TemplateEngine and prepares it for usage
133 * @param $basePath The local base path for all templates
134 * @param $langInstance An instance of LanguageSystem (default)
135 * @param $ioInstance An instance of FileIoHandler (default, middleware!)
136 * @return $tplInstance An instance of TemplateEngine
137 * @throws BasePathIsEmptyException If the provided $basePath is empty
138 * @throws InvalidBasePathStringException If $basePath is no string
139 * @throws BasePathIsNoDirectoryException If $basePath is no
140 * directory or not found
141 * @throws BasePathReadProtectedException If $basePath is
144 public final static function createTemplateEngine ($basePath, ManageableLanguage $langInstance, FileIoHandler $ioInstance) {
145 // Get a new instance
146 $tplInstance = new TemplateEngine();
148 // Is the base path valid?
149 if (empty($basePath)) {
150 // Base path is empty
151 throw new BasePathIsEmptyException($tplInstance, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
152 } elseif (!is_string($basePath)) {
154 throw new InvalidBasePathStringException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_STRING);
155 } elseif (!is_dir($basePath)) {
157 throw new BasePathIsNoDirectoryException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_PATH_NAME);
158 } elseif (!is_readable($basePath)) {
160 throw new BasePathReadProtectedException(array($tplInstance, $basePath), self::EXCEPTION_READ_PROTECED_PATH);
163 // Get configuration instance
164 $cfgInstance = FrameworkConfiguration::getInstance();
167 $tplInstance->setBasePath($basePath);
169 // Initialize the variable stack
170 $tplInstance->initVariableStack();
172 // Set the language and IO instances
173 $tplInstance->setLanguageInstance($langInstance);
174 $tplInstance->setFileIoInstance($ioInstance);
176 // Set template extensions
177 $tplInstance->setRawTemplateExtension($cfgInstance->readConfig('raw_template_extension'));
178 $tplInstance->setCodeTemplateExtension($cfgInstance->readConfig('code_template_extension'));
180 // Absolute output path for compiled templates
181 $tplInstance->setCompileOutputPath(PATH . $cfgInstance->readConfig('compile_output_path'));
183 // Return the prepared instance
188 * Search for a variable in the stack
190 * @param $var The variable we are looking for
191 * @return $idx FALSE means not found, >=0 means found on a specific index
193 private function isVariableAlreadySet ($var) {
194 // First everything is not found
198 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
200 $currEntry = $idx->current();
202 // Is the entry found?
203 if ($currEntry['name'] == $var) {
205 $found = $idx->key();
210 // Return the current position
215 * Return a content of a variable or null if not found
217 * @param $var The variable we are looking for
218 * @return $content Content of the variable or null if not found
220 private function readVariable ($var) {
221 // First everything is not found
225 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
227 $currEntry = $idx->current();
229 // Is the entry found?
230 if ($currEntry['name'] == $var) {
232 $content = $currEntry['value'];
237 // Return the current position
242 * Add a variable to the stack
244 * @param $var The variable we are looking for
245 * @param $value The value we want to store in the variable
248 private function addVariable ($var, $value) {
249 // Add it to the stack
250 $this->varStack->append(array(
251 'name' => trim($var),
252 'value' => trim($value)
257 * Modify an entry on the stack
259 * @param $var The variable we are looking for
260 * @param $value The value we want to store in the variable
263 private function modifyVariable ($var, $value) {
264 // It should be there so let's look again...
265 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
267 $currEntry = $idx->current();
269 // Is this the requested variable?
270 if ($currEntry['name'] == $var) {
271 // Change it to the other value
272 $this->varStack->offsetSet($idx->key(), array(
281 * Initialize the variable stack. This holds all variables for later
286 public final function initVariableStack () {
287 $this->varStack = new FrameworkArrayObject("FakedVariableStack");
291 * Setter for base path
293 * @param $basePath The local base path for all templates
296 public final function setBasePath ($basePath) {
298 $basePath = (string) $basePath;
301 $this->basePath = $basePath;
305 * Getter for base path
307 * @return $basePath The local base path for all templates
309 public final function getBasePath () {
311 return $this->basePath;
315 * Setter for template extension
317 * @param $templateExtension The file extension for all uncompiled
321 public final function setRawTemplateExtension ($templateExtension) {
323 $templateExtension = (string) $templateExtension;
326 $this->templateExtension = $templateExtension;
330 * Setter for code template extension
332 * @param $codeExtension The file extension for all uncompiled
336 public final function setCodeTemplateExtension ($codeExtension) {
338 $codeExtension = (string) $codeExtension;
341 $this->codeExtension = $codeExtension;
345 * Getter for template extension
347 * @return $templateExtension The file extension for all uncompiled
350 public final function getRawTemplateExtension () {
352 return $this->templateExtension;
356 * Getter for code-template extension
358 * @return $codeExtension The file extension for all code-
361 public final function getCodeTemplateExtension () {
363 return $this->codeExtension;
367 * Setter for path of compiled templates
369 * @param $compileOutputPath The local base path for all
373 public final function setCompileOutputPath ($compileOutputPath) {
375 $compileOutputPath = (string) $compileOutputPath;
378 $this->compileOutputPath = $compileOutputPath;
382 * Setter for template type. Only "html", "emails" and "compiled" should
385 * @param $templateType The current template's type
388 private final function setTemplateType ($templateType) {
390 $templateType = (string) $templateType;
392 // And set it (only 2 letters)
393 $this->templateType = $templateType;
397 * Getter for template type
399 * @return $templateType The current template's type
401 public final function getTemplateType () {
402 return $this->templateType;
406 * Setter for the last loaded template's FQFN
408 * @param $template The last loaded template
411 private final function setLastTemplate ($template) {
413 $template = (string) $template;
414 $this->lastTemplate = $template;
418 * Getter for the last loaded template's FQFN
420 * @return $template The last loaded template
422 private final function getLastTemplate () {
423 return $this->lastTemplate;
427 * Assign (add) a given variable with a value
429 * @param $var The variable we are looking for
430 * @param $value The value we want to store in the variable
433 public final function assignVariable ($var, $value) {
434 // First search for the variable if it was already added
435 $idx = $this->isVariableAlreadySet($var);
438 if ($idx === false) {
439 // Add it to the stack
440 $this->addVariable($var, $value);
441 } elseif (!empty($value)) {
442 // Modify the stack entry
443 $this->modifyVariable($var, $value);
448 * Assign a given congfiguration variable with a value
450 * @param $var The configuration variable we are looking for
451 * @param $value The value we want to store in the variable
454 public final function assignConfigVariable ($var, $value) {
455 // Sweet and simple...
456 $this->configVariables[$var] = $value;
460 * Removes a given variable
462 * @param $var The variable we are looking for
465 public final function removeVariable ($var) {
466 // First search for the variable if it was already added
467 $idx = $this->isVariableAlreadySet($var);
470 if ($idx !== false) {
471 // Remove this variable
472 $this->varStack->offsetUnset($idx);
477 * Private setter for raw template data
479 * @param $rawTemplateData The raw data from the template
482 private final function setRawTemplateData ($rawTemplateData) {
484 $rawTemplateData = (string) $rawTemplateData;
486 // And store it in this class
487 $this->rawTemplateData = $rawTemplateData;
491 * Private setter for compiled templates
493 private final function setCompiledData ($compiledData) {
495 $compiledData = (string) $compiledData;
497 // And store it in this class
498 $this->compiledData = $compiledData;
502 * Private loader for all template types
504 * @param $template The template we shall load
507 private final function loadTemplate ($template) {
509 $template = (string) $template;
511 // Get extension for the template
512 $ext = $this->getRawTemplateExtension();
514 // If we shall load a code-template we need to switch the file extension
515 if ($this->getTemplateType() == $this->getConfigInstance()->readConfig('code_template_type')) {
516 // Switch over to the code-template extension
517 $ext = $this->getCodeTemplateExtension();
520 // Construct the FQFN for the template by honoring the current language
521 $fqfn = sprintf("%s%s/%s/%s%s",
522 $this->getBasePath(),
523 $this->getLanguageInstance()->getLanguageCode(),
524 $this->getTemplateType(),
529 // Load the raw template data
530 $this->loadRawTemplateData($fqfn);
534 * A private loader for raw template names
536 * @param $fqfn The full-qualified file name for a template
538 * @throws NullPointerException If $inputInstance is null
539 * @throws NoObjectException If $inputInstance is not an object
540 * @throws MissingMethodException If $inputInstance is missing a
543 private function loadRawTemplateData ($fqfn) {
544 // Get a input/output instance from the middleware
545 $ioInstance = $this->getFileIoInstance();
547 // Validate the instance
548 if (is_null($ioInstance)) {
550 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
551 } elseif (!is_object($ioInstance)) {
552 // Throw another exception
553 throw new NoObjectException($ioInstance, self::EXCEPTION_IS_NO_OBJECT);
554 } elseif (!method_exists($ioInstance, 'loadFileContents')) {
555 // Throw yet another exception
556 throw new MissingMethodException(array($ioInstance, 'loadFileContents'), self::EXCEPTION_MISSING_METHOD);
559 // Load the raw template
560 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
562 // Store the template's contents into this class
563 $this->setRawTemplateData($rawTemplateData);
565 // Remember the template's FQFN
566 $this->setLastTemplate($fqfn);
570 * Try to assign an extracted template variable as a "content" or "config"
573 * @param $varName The variable's name (shall be content or
575 * @param $var The variable we want to assign
577 private function assignTemplateVariable ($varName, $var) {
578 // Is it not a config variable?
579 if ($varName != "config") {
580 // Regular template variables
581 $this->assignVariable($var, "");
583 // Configuration variables
584 $this->assignConfigVariable($var, $this->getConfigInstance()->readConfig($var));
589 * Extract variables from a given raw data stream
591 * @param $rawData The raw template data we shall analyze
594 private function extractVariablesFromRawData ($rawData) {
596 $rawData = (string) $rawData;
598 // Search for variables
599 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
601 // Did we find some variables?
602 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
603 // Initialize all missing variables
604 foreach ($variableMatches[3] as $key=>$var) {
605 // Try to assign it, empty strings are being ignored
606 $this->assignTemplateVariable($variableMatches[1][$key], $var);
612 * Main analysis of the loaded template
614 * @param $templateMatches Found template place-holders, see below
617 *---------------------------------
618 * Structure of $templateMatches:
619 *---------------------------------
620 * [0] => Array - An array with all full matches
621 * [1] => Array - An array with left part (before the ":") of a match
622 * [2] => Array - An array with right part of a match including ":"
623 * [3] => Array - An array with right part of a match excluding ":"
625 private function analyzeTemplate (array $templateMatches) {
626 // Backup raw template data
627 $backup = $this->getRawTemplateData();
629 // Initialize some arrays
630 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
632 // Load all requested templates
633 foreach ($templateMatches[1] as $template) {
635 // Load and compile only templates which we have not yet loaded
636 // RECURSIVE PROTECTION! BE CAREFUL HERE!
637 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
639 // Template not found, but maybe variable assigned?
640 if ($this->isVariableAlreadySet($template) !== false) {
641 // Use that content here
642 $this->loadedRawData[$template] = $this->readVariable($template);
644 // Recursive protection:
645 $this->loadedTemplates[] = $template;
647 // Then try to search for code-templates
649 // Load the code template and remember it's contents
650 $this->loadCodeTemplate($template);
651 $this->loadedRawData[$template] = $this->getRawTemplateData();
653 // Remember this template for recursion detection
654 // RECURSIVE PROTECTION!
655 $this->loadedTemplates[] = $template;
656 } catch (FilePointerNotOpenedException $e) {
657 // Even this is not done... :/
658 $this->rawTemplates[] = $template;
662 } // if ((!isset( ...
664 } // for ($templateMatches ...
666 // Restore the raw template data
667 $this->setRawTemplateData($backup);
671 * Compile a given raw template code and remember it for later usage
673 * @param $code The raw template code
674 * @param $template The template's name
677 private function compileCode ($code, $template) {
678 // Is this template already compiled?
679 if (in_array($template, $this->compiledTemplates)) {
684 // Remember this template being compiled
685 $this->compiledTemplates[] = $template;
687 // Compile the loaded code in five steps:
689 // 1. Backup current template data
690 $backup = $this->getRawTemplateData();
692 // 2. Set the current template's raw data as the new content
693 $this->setRawTemplateData($code);
695 // 3. Compile the template data
696 $this->compileTemplate();
698 // 4. Remember it's contents
699 $this->loadedRawData[$template] = $this->getRawTemplateData();
701 // 5. Restore the previous raw content from backup variable
702 $this->setRawTemplateData($backup);
706 * Insert all given and loaded templates by running through all loaded
707 * codes and searching for their place-holder in the main template
709 * @param $templateMatches See method analyzeTemplate()
712 private function insertAllTemplates (array $templateMatches) {
713 // Run through all loaded codes
714 foreach ($this->loadedRawData as $template=>$code) {
716 // Search for the template
717 $foundIndex = array_search($template, $templateMatches[1]);
719 // Lookup the matching template replacement
720 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
722 // Get the current raw template
723 $rawData = $this->getRawTemplateData();
725 // Replace the space holder with the template code
726 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
728 // Set the new raw data
729 $this->setRawTemplateData($rawData);
737 * Load all extra raw templates
741 private function loadExtraRawTemplates () {
742 // Are there some raw templates we need to load?
743 if (count($this->rawTemplates) > 0) {
744 // Try to load all raw templates
745 foreach ($this->rawTemplates as $key => $template) {
748 $this->loadWebTemplate($template);
750 // Remember it's contents
751 $this->rawTemplates[$template] = $this->getRawTemplateData();
753 // Remove it from the loader list
754 unset($this->rawTemplates[$key]);
756 // Remember this template for recursion detection
757 // RECURSIVE PROTECTION!
758 $this->loadedTemplates[] = $template;
759 } catch (FilePointerNotOpenedException $e) {
760 // This template was never found. We silently ignore it
761 unset($this->rawTemplates[$key]);
768 * Assign all found template variables
770 * @param $varMatches An array full of variable/value pairs.
773 private function assignAllVariables (array $varMatches) {
774 // Search for all variables
775 foreach ($varMatches[1] as $key=>$var) {
777 // Detect leading equals
778 if (substr($varMatches[2][$key], 0, 1) == "=") {
779 // Remove and cast it
780 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
783 // Do we have some quotes left and right side? Then it is free text
784 if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
785 // Free string detected! Which we can assign directly
786 $this->assignVariable($var, $varMatches[3][$key]);
787 } elseif (!empty($varMatches[2][$key])) {
788 // Non-string found so we need some deeper analysis...
789 // @TODO Unfinished work or don't die here.
790 die("Deeper analysis not yet implemented!");
793 } // for ($varMatches ...
796 * Compiles all loaded raw templates
798 * @param $templateMatches See method analyzeTemplate() for details
801 private function compileRawTemplateData (array $templateMatches) {
802 // Are some code-templates found which we need to compile?
803 if (count($this->loadedRawData) > 0) {
806 foreach ($this->loadedRawData as $template=>$code) {
808 // Is this template already compiled?
809 if (in_array($template, $this->compiledTemplates)) {
814 // Search for the template
815 $foundIndex = array_search($template, $templateMatches[1]);
817 // Lookup the matching variable data
818 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
820 // Split it up with another reg. exp. into variable=value pairs
821 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
823 // Assign all variables
824 $this->assignAllVariables($varMatches);
826 } // END - if (isset($templateMatches ...
828 // Compile the loaded template
829 $this->compileCode($code, $template);
831 } // END - foreach ($this->loadedRawData ...
833 // Insert all templates
834 $this->insertAllTemplates($templateMatches);
836 } // END - if (count($this->loadedRawData) ...
840 * Inserts all raw templates into their respective variables
844 private function insertRawTemplates () {
845 // Load all templates
846 foreach ($this->rawTemplates as $template=>$content) {
847 // Set the template as a variable with the content
848 $this->assignVariable($template, $content);
853 * Finalizes the compilation of all template variables
857 private function finalizeVariableCompilation () {
859 $content = $this->getRawTemplateData();
861 // Walk through all variables
862 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
864 $currEntry = $idx->current();
866 // Replace all [$var] or {?$var?} with the content
867 //* DEBUG: */ echo "name=".$currEntry['name'].", value=<pre>".htmlentities($currEntry['value'])."</pre>\n";
868 $content = str_replace("\$content[".$currEntry['name']."]", $currEntry['value'], $content);
869 $content = str_replace("[".$currEntry['name']."]", $currEntry['value'], $content);
870 $content = str_replace("{?".$currEntry['name']."?}", $currEntry['value'], $content);
873 // Set the content back
874 $this->setRawTemplateData($content);
878 * Getter for raw template data
880 * @return $rawTemplateData The raw data from the template
882 public final function getRawTemplateData () {
883 return $this->rawTemplateData;
887 * Getter for compiled templates
889 public final function getCompiledData () {
890 return $this->compiledData;
894 * Load a specified web template into the engine
896 * @param $template The web template we shall load which is
897 * located in "html" by default
900 public final function loadWebTemplate ($template) {
902 $this->setTemplateType($this->getConfigInstance()->readConfig('web_template_type'));
904 // Load the special template
905 $this->loadTemplate($template);
909 * Load a specified email template into the engine
911 * @param $template The email template we shall load which is
912 * located in "emails" by default
915 public final function loadEmailTemplate ($template) {
917 $this->setTemplateType($this->getConfigInstance()->readConfig('email_template_type'));
919 // Load the special template
920 $this->loadTemplate($template);
924 * Load a specified code template into the engine
926 * @param $template The code template we shall load which is
927 * located in "code" by default
930 public final function loadCodeTemplate ($template) {
932 $this->setTemplateType($this->getConfigInstance()->readConfig('code_template_type'));
934 // Load the special template
935 $this->loadTemplate($template);
939 * Compile all variables by inserting their respective values
943 public final function compileVariables () {
944 // Initialize the $content array
945 $validVar = $this->getConfigInstance()->readConfig('tpl_valid_var');
948 // Iterate through all variables
949 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
951 // Get current variable from the stack
952 $currVariable = $idx->current();
954 // Transfer it's name/value combination to the $content array
955 //* DEBUG: */ echo $currVariable['name']."=<pre>".htmlentities($currVariable['value'])."</pre>\n";
956 $dummy[$currVariable['name']] = $currVariable['value'];
960 // Set the new variable (don't remove the second dollar !)
963 // Prepare all configuration variables
964 $config = $this->configVariables;
966 // Remove some variables
968 unset($currVariable);
970 // Run the compilation twice to get content from helper classes in
973 // Finalize the compilation of template variables
974 $this->finalizeVariableCompilation();
976 // Prepare the eval() command for comiling the template
977 $eval = sprintf("\$result = \"%s\";",
978 addslashes($this->getRawTemplateData())
981 // This loop does remove the backslashes (\) in PHP parameters
982 // @TODO Make this some nicer...
983 while (strpos($eval, "<?") !== false) {
984 // Get left part before "<?"
985 $evalLeft = substr($eval, 0, strpos($eval, "<?"));
987 // Get all from right of "<?"
988 $evalRight = substr($eval, (strpos($eval, "<?") + 2));
990 // Is this a full PHP tag?
991 if (substr(strtolower($evalRight), 0, 3) == "php") {
992 // Remove "php" string from full PHP tag
993 $evalRight = substr($evalRight, 3);
996 // Cut middle part out and remove escapes
997 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, "?>")));
998 $evalMiddle = stripslashes($evalMiddle);
1000 // Remove the middle part from right one
1001 $evalRight = substr($evalRight, (strpos($evalRight, "?>") + 2));
1003 // And put all together
1004 $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
1007 // Prepare PHP code for eval() command
1008 $eval = str_replace(
1011 "%>", "\$result .= \"", $eval
1016 if ((defined('DEBUG_EVAL')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Constructed PHP command: <pre><em>%s</em></pre><br />\n",
1017 $this->__toString(),
1021 // Run the constructed command. This will "compile" all variables in
1024 // Set raw template data
1025 $this->setRawTemplateData($result);
1029 // Set the new content
1030 $this->setCompiledData($result);
1034 * Compile all required templates into the current loaded one
1037 * @throws UnexpectedTemplateTypeException If the template type is
1039 * @throws InvalidArrayCountException If an unexpected array
1040 * count has been found
1042 public final function compileTemplate () {
1043 // We will only work with template type "code" from configuration
1044 if ($this->getTemplateType() != $this->getConfigInstance()->readConfig('code_template_type')) {
1046 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->readConfig('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1049 // Get the raw data.
1050 $rawData = $this->getRawTemplateData();
1052 // Remove double spaces and trim leading/trailing spaces
1053 $rawData = trim(str_replace(" ", " ", $rawData));
1055 // Search for raw variables
1056 $this->extractVariablesFromRawData($rawData);
1058 // Search for code-tags which are {? ?}
1059 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1061 // Analyze the matches array
1062 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1063 // Entries are found:
1065 // The main analysis
1066 $this->analyzeTemplate($templateMatches);
1068 // Compile raw template data
1069 $this->compileRawTemplateData($templateMatches);
1071 // Are there some raw templates left for loading?
1072 $this->loadExtraRawTemplates();
1074 // Are some raw templates found and loaded?
1075 if (count($this->rawTemplates) > 0) {
1077 // Insert all raw templates
1078 $this->insertRawTemplates();
1080 // Remove the raw template content as well
1081 $this->setRawTemplateData("");
1085 } // END - if($templateMatches ...
1089 * Output the compiled page to the outside world. In case of web templates
1090 * this would be vaild (X)HTML code. And in case of email templates this
1091 * would store a prepared email body inside the template engine.
1095 public final function output () {
1096 // Check which type of template we have
1097 switch ($this->getTemplateType()) {
1098 case "html": // Raw HTML templates can be send to the output buffer
1100 $this->getWebOutputInstance()->output($this->getCompiledData());
1103 default: // Unknown type found
1104 // Construct message
1105 $msg = sprintf("[%s:] Unknown/unsupported template type <strong>%s</strong> detected.",
1106 $this->__toString(),
1107 $this->getTemplateType()
1110 if ((is_object($this->getDebugInstance())) && (method_exists($this->getDebugInstance(), 'output'))) {
1111 // Use debug output handler
1112 $this->getDebugInstance()->output($msg);
1116 // DO NOT REWRITE THIS TO app_die() !!!
1124 * Loads a given view helper (by name)
1126 * @param $helperName The helper's name
1128 * @throws ViewHelperNotFoundException If the given view helper was not found
1130 protected function loadViewHelper ($helperName) {
1131 // Make first character upper case, rest low
1132 $helperName = ucfirst($helperName);
1134 // Is this view helper loaded?
1135 if (!isset($this->helpers[$helperName])) {
1136 // Create a class name
1137 $className = "{$helperName}ViewHelper";
1139 // Does this class exists?
1140 if (!class_exists($className)) {
1142 throw new ViewHelperNotFoundException(array($this, $helperName), self::EXCEPTION_INVALID_VIEW_HELPER);
1145 // Generate new instance
1146 $eval = sprintf("\$this->helpers[%s] = %s::create%s();",
1156 // Return the requested instance
1157 return $this->helpers[$helperName];
1161 * Assigns the last loaded raw template content with a given variable
1163 * @param $templateName Name of the template we want to assign
1164 * @param $variableName Name of the variable we want to assign
1167 public function assignTemplateWithVariable ($templateName, $variableName) {
1168 // Get the content from last loaded raw template
1169 $content = $this->getRawTemplateData();
1171 // Assign the variable
1172 $this->assignVariable($variableName, $content);
1174 // Purge raw content
1175 $this->setRawTemplateData("");
1179 * Transfers the content of this template engine to a given response instance
1181 * @param $responseInstance An instance of a response class
1184 public function transferToResponse (Responseable $responseInstance) {
1185 // Get the content and set it in the response class
1186 $responseInstance->writeToBody($this->getCompiledData());
1190 * Assigns all the application data with template variables
1192 * @param $appInstance A manageable application instance
1195 public function assignApplicationData (ManageableApplication $appInstance) {
1196 // Get long name and assign it
1197 $this->assignVariable("app_full_name" , $appInstance->getAppName());
1199 // Get short name and assign it
1200 $this->assignVariable("app_short_name", $appInstance->getAppShortName());
1202 // Get version number and assign it
1203 $this->assignVariable("app_version" , $appInstance->getAppVersion());