3 * The own template engine for loading caching and sending out the web pages
6 * @author Roland Haeder <webmaster@mxchange.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 = 0xa00;
113 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0xa01;
114 const EXCEPTION_INVALID_VIEW_HELPER = 0xa02;
117 * Protected constructor
121 protected function __construct () {
122 // Call parent constructor
123 parent::__construct(__CLASS__);
125 // Set part description
126 $this->setObjectDescription("Template-Engine");
128 // Create unique ID number
129 $this->createUniqueID();
132 $this->removeNumberFormaters();
133 $this->removeSystemArray();
137 * Creates an instance of the class TemplateEngine and prepares it for usage
139 * @param $basePath The local base path for all templates
140 * @param $langInstance An instance of LanguageSystem (default)
141 * @param $ioInstance An instance of FileIoHandler (default, middleware!)
142 * @return $tplInstance An instance of TemplateEngine
143 * @throws BasePathIsEmptyException If the provided $basePath is empty
144 * @throws InvalidBasePathStringException If $basePath is no string
145 * @throws BasePathIsNoDirectoryException If $basePath is no
146 * directory or not found
147 * @throws BasePathReadProtectedException If $basePath is
150 public final static function createTemplateEngine ($basePath, ManageableLanguage $langInstance, FileIoHandler $ioInstance) {
151 // Get a new instance
152 $tplInstance = new TemplateEngine();
154 // Is the base path valid?
155 if (empty($basePath)) {
156 // Base path is empty
157 throw new BasePathIsEmptyException($tplInstance, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
158 } elseif (!is_string($basePath)) {
160 throw new InvalidBasePathStringException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_STRING);
161 } elseif (!is_dir($basePath)) {
163 throw new BasePathIsNoDirectoryException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_PATH_NAME);
164 } elseif (!is_readable($basePath)) {
166 throw new BasePathReadProtectedException(array($tplInstance, $basePath), self::EXCEPTION_READ_PROTECED_PATH);
169 // Get configuration instance
170 $cfgInstance = FrameworkConfiguration::getInstance();
173 $tplInstance->setBasePath($basePath);
175 // Initialize the variable stack
176 $tplInstance->initVariableStack();
178 // Set the language and IO instances
179 $tplInstance->setLanguageInstance($langInstance);
180 $tplInstance->setFileIoInstance($ioInstance);
182 // Set template extensions
183 $tplInstance->setRawTemplateExtension($cfgInstance->readConfig("raw_template_extension"));
184 $tplInstance->setCodeTemplateExtension($cfgInstance->readConfig("code_template_extension"));
186 // Absolute output path for compiled templates
187 $tplInstance->setCompileOutputPath(PATH . $cfgInstance->readConfig("compile_output_path"));
189 // Return the prepared instance
194 * Search for a variable in the stack
196 * @param $var The variable we are looking for
197 * @return $idx FALSE means not found, >=0 means found on a specific index
199 private function isVariableAlreadySet ($var) {
200 // First everything is not found
204 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
206 $currEntry = $idx->current();
208 // Is the entry found?
209 if ($currEntry['name'] == $var) {
211 $found = $idx->key();
216 // Return the current position
221 * Return a content of a variable or null if not found
223 * @param $var The variable we are looking for
224 * @return $content Content of the variable or null if not found
226 private function readVariable ($var) {
227 // First everything is not found
231 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
233 $currEntry = $idx->current();
235 // Is the entry found?
236 if ($currEntry['name'] == $var) {
238 $content = $currEntry['value'];
243 // Return the current position
248 * Add a variable to the stack
250 * @param $var The variable we are looking for
251 * @param $value The value we want to store in the variable
254 private function addVariable ($var, $value) {
255 // Add it to the stack
256 $this->varStack->append(array(
257 'name' => trim($var),
258 'value' => trim($value)
263 * Modify an entry on the stack
265 * @param $var The variable we are looking for
266 * @param $value The value we want to store in the variable
269 private function modifyVariable ($var, $value) {
270 // It should be there so let's look again...
271 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
273 $currEntry = $idx->current();
275 // Is this the requested variable?
276 if ($currEntry['name'] == $var) {
277 // Change it to the other value
278 $this->varStack->offsetSet($idx->key(), array(
287 * Initialize the variable stack. This holds all variables for later
292 public final function initVariableStack () {
293 $this->varStack = new FrameworkArrayObject();
297 * Setter for base path
299 * @param $basePath The local base path for all templates
302 public final function setBasePath ($basePath) {
304 $basePath = (string) $basePath;
307 $this->basePath = $basePath;
311 * Getter for base path
313 * @return $basePath The local base path for all templates
315 public final function getBasePath () {
317 return $this->basePath;
321 * Setter for template extension
323 * @param $templateExtension The file extension for all uncompiled
327 public final function setRawTemplateExtension ($templateExtension) {
329 $templateExtension = (string) $templateExtension;
332 $this->templateExtension = $templateExtension;
336 * Setter for code template extension
338 * @param $codeExtension The file extension for all uncompiled
342 public final function setCodeTemplateExtension ($codeExtension) {
344 $codeExtension = (string) $codeExtension;
347 $this->codeExtension = $codeExtension;
351 * Getter for template extension
353 * @return $templateExtension The file extension for all uncompiled
356 public final function getRawTemplateExtension () {
358 return $this->templateExtension;
362 * Getter for code-template extension
364 * @return $codeExtension The file extension for all code-
367 public final function getCodeTemplateExtension () {
369 return $this->codeExtension;
373 * Setter for path of compiled templates
375 * @param $compileOutputPath The local base path for all
379 public final function setCompileOutputPath ($compileOutputPath) {
381 $compileOutputPath = (string) $compileOutputPath;
384 $this->compileOutputPath = $compileOutputPath;
388 * Setter for template type. Only "html", "emails" and "compiled" should
391 * @param $templateType The current template's type
394 private final function setTemplateType ($templateType) {
396 $templateType = (string) $templateType;
398 // And set it (only 2 letters)
399 $this->templateType = $templateType;
403 * Getter for template type
405 * @return $templateType The current template's type
407 public final function getTemplateType () {
408 return $this->templateType;
412 * Setter for the last loaded template's FQFN
414 * @param $template The last loaded template
417 private final function setLastTemplate ($template) {
419 $template = (string) $template;
420 $this->lastTemplate = $template;
424 * Getter for the last loaded template's FQFN
426 * @return $template The last loaded template
428 private final function getLastTemplate () {
429 return $this->lastTemplate;
433 * Assign (add) a given variable with a value
435 * @param $var The variable we are looking for
436 * @param $value The value we want to store in the variable
439 public final function assignVariable ($var, $value) {
440 // First search for the variable if it was already added
441 $idx = $this->isVariableAlreadySet($var);
444 if ($idx === false) {
445 // Add it to the stack
446 $this->addVariable($var, $value);
447 } elseif (!empty($value)) {
448 // Modify the stack entry
449 $this->modifyVariable($var, $value);
454 * Assign a given congfiguration variable with a value
456 * @param $var The configuration variable we are looking for
457 * @param $value The value we want to store in the variable
460 public final function assignConfigVariable ($var, $value) {
461 // Sweet and simple...
462 $this->configVariables[$var] = $value;
466 * Removes a given variable
468 * @param $var The variable we are looking for
471 public final function removeVariable ($var) {
472 // First search for the variable if it was already added
473 $idx = $this->isVariableAlreadySet($var);
476 if ($idx !== false) {
477 // Remove this variable
478 $this->varStack->offsetUnset($idx);
483 * Private setter for raw template data
485 * @param $rawTemplateData The raw data from the template
488 private final function setRawTemplateData ($rawTemplateData) {
490 $rawTemplateData = (string) $rawTemplateData;
492 // And store it in this class
493 $this->rawTemplateData = $rawTemplateData;
497 * Private setter for compiled templates
499 private final function setCompiledData ($compiledData) {
501 $compiledData = (string) $compiledData;
503 // And store it in this class
504 $this->compiledData = $compiledData;
508 * Private loader for all template types
510 * @param $template The template we shall load
513 private final function loadTemplate ($template) {
515 $template = (string) $template;
517 // Get extension for the template
518 $ext = $this->getRawTemplateExtension();
520 // If we shall load a code-template we need to switch the file extension
521 if ($this->getTemplateType() == $this->getConfigInstance()->readConfig("code_template_type")) {
522 // Switch over to the code-template extension
523 $ext = $this->getCodeTemplateExtension();
526 // Construct the FQFN for the template by honoring the current language
527 $fqfn = sprintf("%s%s/%s/%s%s",
528 $this->getBasePath(),
529 $this->getLanguageInstance()->getLanguageCode(),
530 $this->getTemplateType(),
535 // Load the raw template data
536 $this->loadRawTemplateData($fqfn);
540 * A private loader for raw template names
542 * @param $fqfn The full-qualified file name for a template
544 * @throws NullPointerException If $inputInstance is null
545 * @throws NoObjectException If $inputInstance is not an object
546 * @throws MissingMethodException If $inputInstance is missing a
549 private function loadRawTemplateData ($fqfn) {
550 // Get a input/output instance from the middleware
551 $ioInstance = $this->getFileIoInstance();
553 // Validate the instance
554 if (is_null($ioInstance)) {
556 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
557 } elseif (!is_object($ioInstance)) {
558 // Throw another exception
559 throw new NoObjectException($ioInstance, self::EXCEPTION_IS_NO_OBJECT);
560 } elseif (!method_exists($ioInstance, 'loadFileContents')) {
561 // Throw yet another exception
562 throw new MissingMethodException(array($ioInstance, 'loadFileContents'), self::EXCEPTION_MISSING_METHOD);
565 // Load the raw template
566 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
568 // Store the template's contents into this class
569 $this->setRawTemplateData($rawTemplateData);
571 // Remember the template's FQFN
572 $this->setLastTemplate($fqfn);
576 * Try to assign an extracted template variable as a "content" or "config"
579 * @param $varName The variable's name (shall be content or
581 * @param $var The variable we want to assign
583 private function assignTemplateVariable ($varName, $var) {
584 // Is it not a config variable?
585 if ($varName != "config") {
586 // Regular template variables
587 $this->assignVariable($var, "");
589 // Configuration variables
590 $this->assignConfigVariable($var, $this->getConfigInstance()->readConfig($var));
595 * Extract variables from a given raw data stream
597 * @param $rawData The raw template data we shall analyze
599 * @throws InvalidTemplateVariableNameException If a variable name
603 private function extractVariablesFromRawData ($rawData) {
605 $rawData = (string) $rawData;
607 // Search for variables
608 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
610 // Did we find some variables?
611 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
612 // Initialize all missing variables
613 foreach ($variableMatches[3] as $key=>$var) {
614 // Try to assign it, empty strings are being ignored
615 $this->assignTemplateVariable($variableMatches[1][$key], $var);
621 * Main analysis of the loaded template
623 * @param $templateMatches Found template place-holders, see below
626 *---------------------------------
627 * Structure of $templateMatches:
628 *---------------------------------
629 * [0] => Array - An array with all full matches
630 * [1] => Array - An array with left part (before the ":") of a match
631 * [2] => Array - An array with right part of a match including ":"
632 * [3] => Array - An array with right part of a match excluding ":"
634 private function analyzeTemplate (array $templateMatches) {
635 // Backup raw template data
636 $backup = $this->getRawTemplateData();
638 // Initialize some arrays
639 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
641 // Load all requested templates
642 foreach ($templateMatches[1] as $template) {
644 // Load and compile only templates which we have not yet loaded
645 // RECURSIVE PROTECTION! BE CAREFUL HERE!
646 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
648 // Then try to search for code-templates first
650 // Load the code template and remember it's contents
651 $this->loadCodeTemplate($template);
652 $this->loadedRawData[$template] = $this->getRawTemplateData();
654 // Remember this template for recursion detection
655 // RECURSIVE PROTECTION!
656 $this->loadedTemplates[] = $template;
657 } catch (FilePointerNotOpenedException $e) {
658 // Template not found, but maybe variable assigned?
659 if ($this->isVariableAlreadySet($template) !== false) {
660 // Use that content here
661 $this->loadedRawData[$template] = $this->readVariable($template);
663 // Recursive protection:
664 $this->loadedTemplates[] = $template;
666 // Even this is not done... :/
667 $this->rawTemplates[] = $template;
671 } // if ((!isset( ...
673 } // for ($templateMatches ...
675 // Restore the raw template data
676 $this->setRawTemplateData($backup);
680 * Compile a given raw template code and remember it for later usage
682 * @param $code The raw template code
683 * @param $template The template's name
686 private function compileCode ($code, $template) {
687 // Is this template already compiled?
688 if (in_array($template, $this->compiledTemplates)) {
693 // Remember this template being compiled
694 $this->compiledTemplates[] = $template;
696 // Compile the loaded code in five steps:
698 // 1. Backup current template data
699 $backup = $this->getRawTemplateData();
701 // 2. Set the current template's raw data as the new content
702 $this->setRawTemplateData($code);
704 // 3. Compile the template data
705 $this->compileTemplate();
707 // 4. Remember it's contents
708 $this->loadedRawData[$template] = $this->getRawTemplateData();
710 // 5. Restore the previous raw content from backup variable
711 $this->setRawTemplateData($backup);
715 * Insert all given and loaded templates by running through all loaded
716 * codes and searching for their place-holder in the main template
718 * @param $templateMatches See method analyzeTemplate()
721 private function insertAllTemplates (array $templateMatches) {
722 // Run through all loaded codes
723 foreach ($this->loadedRawData as $template=>$code) {
725 // Search for the template
726 $foundIndex = array_search($template, $templateMatches[1]);
728 // Lookup the matching template replacement
729 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
731 // Get the current raw template
732 $rawData = $this->getRawTemplateData();
734 // Replace the space holder with the template code
735 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
737 // Set the new raw data
738 $this->setRawTemplateData($rawData);
746 * Load all extra raw templates
750 private function loadExtraRawTemplates () {
751 // Are there some raw templates we need to load?
752 if (count($this->rawTemplates) > 0) {
753 // Try to load all raw templates
754 foreach ($this->rawTemplates as $key => $template) {
757 $this->loadWebTemplate($template);
759 // Remember it's contents
760 $this->rawTemplates[$template] = $this->getRawTemplateData();
762 // Remove it from the loader list
763 unset($this->rawTemplates[$key]);
765 // Remember this template for recursion detection
766 // RECURSIVE PROTECTION!
767 $this->loadedTemplates[] = $template;
768 } catch (FilePointerNotOpenedException $e) {
769 // This template was never found. We silently ignore it
770 unset($this->rawTemplates[$key]);
777 * Assign all found template variables
779 * @param $varMatches An array full of variable/value pairs.
782 private function assignAllVariables (array $varMatches) {
783 // Search for all variables
784 foreach ($varMatches[1] as $key=>$var) {
786 // Detect leading equals
787 if (substr($varMatches[2][$key], 0, 1) == "=") {
788 // Remove and cast it
789 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
792 // Do we have some quotes left and right side? Then it is free text
793 if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
794 // Free string detected! Which we can assign directly
795 $this->assignVariable($var, $varMatches[3][$key]);
796 } elseif (!empty($varMatches[2][$key])) {
797 // Non-string found so we need some deeper analysis...
798 // @TODO Unfinished work or don't die here.
799 die("Deeper analysis not yet implemented!");
802 } // for ($varMatches ...
805 * Compiles all loaded raw templates
807 * @param $templateMatches See method analyzeTemplate() for details
810 private function compileRawTemplateData (array $templateMatches) {
811 // Are some code-templates found which we need to compile?
812 if (count($this->loadedRawData) > 0) {
815 foreach ($this->loadedRawData as $template=>$code) {
817 // Is this template already compiled?
818 if (in_array($template, $this->compiledTemplates)) {
823 // Search for the template
824 $foundIndex = array_search($template, $templateMatches[1]);
826 // Lookup the matching variable data
827 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
829 // Split it up with another reg. exp. into variable=value pairs
830 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
832 // Assign all variables
833 $this->assignAllVariables($varMatches);
835 } // END - if (isset($templateMatches ...
837 // Compile the loaded template
838 $this->compileCode($code, $template);
840 } // END - foreach ($this->loadedRawData ...
842 // Insert all templates
843 $this->insertAllTemplates($templateMatches);
845 } // END - if (count($this->loadedRawData) ...
849 * Inserts all raw templates into their respective variables
853 private function insertRawTemplates () {
854 // Load all templates
855 foreach ($this->rawTemplates as $template=>$content) {
856 // Set the template as a variable with the content
857 $this->assignVariable($template, $content);
862 * Finalizes the compilation of all template variables
866 private function finalizeVariableCompilation () {
868 $content = $this->getRawTemplateData();
870 // Walk through all variables
871 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
873 $currEntry = $idx->current();
875 // Replace all [$var] or {?$var?} with the content
876 //* DEBUG: */ echo "name=".$currEntry['name'].", value=<pre>".htmlentities($currEntry['value'])."</pre>\n";
877 $content = str_replace("\$content[".$currEntry['name']."]", $currEntry['value'], $content);
878 $content = str_replace("[".$currEntry['name']."]", $currEntry['value'], $content);
879 $content = str_replace("{?".$currEntry['name']."?}", $currEntry['value'], $content);
882 // Set the content back
883 $this->setRawTemplateData($content);
887 * Getter for raw template data
889 * @return $rawTemplateData The raw data from the template
891 public final function getRawTemplateData () {
892 return $this->rawTemplateData;
896 * Getter for compiled templates
898 public final function getCompiledData () {
899 return $this->compiledData;
903 * Load a specified web template into the engine
905 * @param $template The web template we shall load which is
906 * located in "html" by default
909 public final function loadWebTemplate ($template) {
911 $this->setTemplateType($this->getConfigInstance()->readConfig("web_template_type"));
913 // Load the special template
914 $this->loadTemplate($template);
918 * Load a specified email template into the engine
920 * @param $template The email template we shall load which is
921 * located in "emails" by default
924 public final function loadEmailTemplate ($template) {
926 $this->setTemplateType($this->getConfigInstance()->readConfig("email_template_type"));
928 // Load the special template
929 $this->loadTemplate($template);
933 * Load a specified code template into the engine
935 * @param $template The code template we shall load which is
936 * located in "code" by default
939 public final function loadCodeTemplate ($template) {
941 $this->setTemplateType($this->getConfigInstance()->readConfig("code_template_type"));
943 // Load the special template
944 $this->loadTemplate($template);
948 * Compile all variables by inserting their respective values
952 public final function compileVariables () {
953 // Initialize the $content array
954 $validVar = $this->getConfigInstance()->readConfig("tpl_valid_var");
957 // Iterate through all variables
958 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
960 // Get current variable from the stack
961 $currVariable = $idx->current();
963 // Transfer it's name/value combination to the $content array
964 //* DEBUG: */ echo $currVariable['name']."=<pre>".htmlentities($currVariable['value'])."</pre>\n";
965 $dummy[$currVariable['name']] = $currVariable['value'];
969 // Set the new variable (don't remove the second dollar !)
972 // Prepare all configuration variables
973 $config = $this->configVariables;
975 // Remove some variables
977 unset($currVariable);
979 // Run the compilation twice to get content from helper classes in
982 // Finalize the compilation of template variables
983 $this->finalizeVariableCompilation();
985 // Prepare the eval() command for comiling the template
986 $eval = sprintf("\$result = \"%s\";",
987 addslashes($this->getRawTemplateData())
990 // This loop does remove the backslashes (\) in PHP parameters
991 // @TODO Make this some nicer...
992 while (strpos($eval, "<?") !== false) {
993 // Get left part before "<?"
994 $evalLeft = substr($eval, 0, strpos($eval, "<?"));
996 // Get all from right of "<?"
997 $evalRight = substr($eval, (strpos($eval, "<?") + 2));
999 // Is this a full PHP tag?
1000 if (substr(strtolower($evalRight), 0, 3) == "php") {
1001 // Remove "php" string from full PHP tag
1002 $evalRight = substr($evalRight, 3);
1005 // Cut middle part out and remove escapes
1006 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, "?>")));
1007 $evalMiddle = stripslashes($evalMiddle);
1009 // Remove the middle part from right one
1010 $evalRight = substr($evalRight, (strpos($evalRight, "?>") + 2));
1012 // And put all together
1013 $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
1016 // Prepare PHP code for eval() command
1017 $eval = str_replace(
1020 "%>", "\$result .= \"", $eval
1025 if ((defined('DEBUG_EVAL')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Constructed PHP command: <pre><em>%s</em></pre><br />\n",
1026 $this->__toString(),
1030 // Run the constructed command. This will "compile" all variables in
1033 // Set raw template data
1034 $this->setRawTemplateData($result);
1038 // Set the new content
1039 $this->setCompiledData($result);
1043 * Compile all required templates into the current loaded one
1046 * @throws UnexpectedTemplateTypeException If the template type is
1048 * @throws InvalidArrayCountException If an unexpected array
1049 * count has been found
1051 public final function compileTemplate () {
1052 // We will only work with template type "code" from configuration
1053 if ($this->getTemplateType() != $this->getConfigInstance()->readConfig("code_template_type")) {
1055 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->readConfig("code_template_type")), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1058 // Get the raw data.
1059 $rawData = $this->getRawTemplateData();
1061 // Remove double spaces and trim leading/trailing spaces
1062 $rawData = trim(str_replace(" ", " ", $rawData));
1064 // Search for raw variables
1065 $this->extractVariablesFromRawData($rawData);
1067 // Search for code-tags which are {? ?}
1068 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1070 // Analyze the matches array
1071 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1072 // Entries are found:
1074 // The main analysis
1075 $this->analyzeTemplate($templateMatches);
1077 // Compile raw template data
1078 $this->compileRawTemplateData($templateMatches);
1080 // Are there some raw templates left for loading?
1081 $this->loadExtraRawTemplates();
1083 // Are some raw templates found and loaded?
1084 if (count($this->rawTemplates) > 0) {
1086 // Insert all raw templates
1087 $this->insertRawTemplates();
1089 // Remove the raw template content as well
1090 $this->setRawTemplateData("");
1094 } // END - if($templateMatches ...
1098 * Output the compiled page to the outside world. In case of web templates
1099 * this would be vaild (X)HTML code. And in case of email templates this
1100 * would store a prepared email body inside the template engine.
1104 public final function output () {
1105 // Check which type of template we have
1106 switch ($this->getTemplateType()) {
1107 case "html": // Raw HTML templates can be send to the output buffer
1109 $this->getWebOutputInstance()->output($this->getCompiledData());
1112 default: // Unknown type found
1113 // Construct message
1114 $msg = sprintf("[%s:] Unknown/unsupported template type <strong>%s</strong> detected.",
1115 $this->__toString(),
1116 $this->getTemplateType()
1119 if ((is_object($this->getDebugInstance())) && (method_exists($this->getDebugInstance(), 'output'))) {
1120 // Use debug output handler
1121 $this->getDebugInstance()->output($msg);
1125 // DO NOT REWRITE THIS TO app_die() !!!
1133 * Loads a given view helper (by name)
1135 * @param $helperName The helper's name
1137 * @throws ViewHelperNotFoundException If the given view helper was not found
1139 protected function loadViewHelper ($helperName) {
1140 // Make first character upper case, rest low
1141 $helperName = ucfirst($helperName);
1143 // Is this view helper loaded?
1144 if (!isset($this->helpers[$helperName])) {
1145 // Create a class name
1146 $className = "{$helperName}ViewHelper";
1148 // Does this class exists?
1149 if (!class_exists($className)) {
1151 throw new ViewHelperNotFoundException(array($this, $helperName), self::EXCEPTION_INVALID_VIEW_HELPER);
1154 // Generate new instance
1155 $eval = sprintf("\$this->helpers[%s] = %s::create%s();",
1165 // Return the requested instance
1166 return $this->helpers[$helperName];
1170 * Assigns the last loaded raw template content with a given variable
1172 * @param $templateName Name of the template we want to assign
1173 * @param $variableName Name of the variable we want to assign
1176 public function assignTemplateWithVariable ($templateName, $variableName) {
1177 // Get the content from last loaded raw template
1178 $content = $this->getRawTemplateData();
1180 // Assign the variable
1181 $this->assignVariable($variableName, $content);
1183 // Purge raw content
1184 $this->setRawTemplateData("");
1188 * Transfers the content of this template engine to a given response instance
1190 * @param $responseInstance An instance of a response class
1193 public function transferToResponse (Responseable $responseInstance) {
1194 // Get the content and set it in the response class
1195 $responseInstance->writeToBody($this->getCompiledData());
1199 * Assigns all the application data with template variables
1201 * @param $appInstance A manageable application instance
1204 public function assignApplicationData (ManageableApplication $appInstance) {
1205 // Get long name and assign it
1206 $this->assignVariable("app_full_name" , $appInstance->getAppName());
1208 // Get short name and assign it
1209 $this->assignVariable("app_short_name", $appInstance->getAppShortName());
1211 // Get version number and assign it
1212 $this->assignVariable("app_version" , $appInstance->getAppVersion());