3 namespace Org\Mxchange\CoreFramework\Template\Engine;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
8 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
9 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
10 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
11 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
12 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
13 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
14 use Org\Mxchange\CoreFramework\Response\Responseable;
15 use Org\Mxchange\CoreFramework\Traits\Handler\Io\IoHandlerTrait;
16 use Org\Mxchange\CoreFramework\Utils\String\StringUtils;
19 use \InvalidArgumentException;
23 * A generic template engine
25 * @author Roland Haeder <webmaster@shipsimu.org>
27 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
28 * @license GNU GPL 3.0 or any newer version
29 * @link http://www.shipsimu.org
31 * This program is free software: you can redistribute it and/or modify
32 * it under the terms of the GNU General Public License as published by
33 * the Free Software Foundation, either version 3 of the License, or
34 * (at your option) any later version.
36 * This program is distributed in the hope that it will be useful,
37 * but WITHOUT ANY WARRANTY; without even the implied warranty of
38 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39 * GNU General Public License for more details.
41 * You should have received a copy of the GNU General Public License
42 * along with this program. If not, see <http://www.gnu.org/licenses/>.
44 abstract class BaseTemplateEngine extends BaseFrameworkSystem {
48 // Exception codes for the template engine
49 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
50 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
51 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
52 const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
55 * The local path name where all templates and sub folders for special
56 * templates are stored. We will internally determine the language plus
57 * "html" for web templates or "emails" for email templates
59 private $templateBasePath = '';
64 private $templateType = 'html';
67 * The extension for web and email templates (not compiled templates)
69 private $templateExtension = '.tpl';
72 * The extension for code templates (not compiled templates)
74 private $codeExtension = '.ctp';
77 * Path relative to $templateBasePath and language code for compiled code-templates
79 private $compileOutputPath = 'templates/_compiled/';
82 * The path name for all templates
84 private $genericBasePath = 'templates/';
87 * The raw (maybe uncompiled) template
89 private $rawTemplateData = '';
92 * Template data with compiled-in variables
94 private $compiledData = '';
97 * The last loaded template's file instance (SplFileInfo)
99 private $lastTemplate = NULL;
102 * The variable stack for the templates
104 private $varStack = [];
107 * Loaded templates for recursive protection and detection
109 private $loadedTemplates = [];
112 * Compiled templates for recursive protection and detection
114 private $compiledTemplates = [];
117 * Loaded raw template data
119 private $loadedRawData = NULL;
122 * Raw templates which are linked in code templates
124 private $rawTemplates = NULL;
127 * A regular expression for variable=value pairs
129 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
132 * A regular expression for filtering out code tags
134 * E.g.: {?template:variable=value;var2=value2;[...]?}
136 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
139 * A regular expression to find template comments like <!-- Comment here //-->
141 private $regExpComments = '/<!--[\w\W]*?(\/\/){0,1}-->/';
146 private $helpers = [];
149 * Current variable group
151 private $currGroup = 'general';
154 * All template groups except "general"
156 private $variableGroups = [];
161 private $codeBegin = '<?php';
166 private $codeEnd = '?>';
169 * Language support is enabled by default
171 private $languageSupport = true;
174 * Protected constructor
176 * @param $className Name of the class
179 protected function __construct (string $className) {
180 // Call parent constructor
181 parent::__construct($className);
183 // Init file I/O instance
184 $ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
187 $this->setFileIoInstance($ioInstance);
191 * Search for a variable in the stack
193 * @param $variableName The variable we are looking for
194 * @param $variableGroup Optional variable group to look in
195 * @return $index false means not found, >=0 means found on a specific index
197 private function getVariableIndex (string $variableName, string $variableGroup = NULL) {
198 // Replace all dashes to underscores to match variables with configuration entries
199 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
201 // First everything is not found
204 // If the stack is NULL, use the current group
205 if (is_null($variableGroup)) {
207 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
208 $variableGroup = $this->currGroup;
211 // Is the group there?
212 if ($this->isVarStackSet($variableGroup)) {
214 foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
215 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
216 // Is the entry found?
217 if ($currEntry['name'] == $variableName) {
219 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':FOUND!');
226 // Return the current position
231 * Checks whether the given variable group is set
233 * @param $variableGroup Variable group to check
234 * @return $isSet Whether the given variable group is set
236 protected final function isVarStackSet (string $variableGroup) {
238 $isSet = isset($this->varStack[$variableGroup]);
245 * Getter for given variable group
247 * @param $variableGroup Variable group to check
248 * @return $varStack Found variable group
250 public final function getVarStack (string $variableGroup) {
251 return $this->varStack[$variableGroup];
255 * Setter for given variable group
257 * @param $variableGroup Variable group to check
258 * @param $varStack Variable stack to check
261 protected final function setVarStack (string $variableGroup, array $varStack) {
262 $this->varStack[$variableGroup] = $varStack;
266 * Return a content of a variable or null if not found
268 * @param $variableName The variable we are looking for
269 * @param $variableGroup Optional variable group to look in
270 * @return $content Content of the variable or null if not found
272 protected function readVariable (string $variableName, string $variableGroup = NULL) {
273 // Replace all dashes to underscores to match variables with configuration entries
274 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
276 // First everything is not found
279 // If the stack is NULL, use the current group
280 if (is_null($variableGroup)) {
282 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
283 $variableGroup = $this->currGroup;
286 // Get variable index
287 $found = $this->getVariableIndex($variableName, $variableGroup);
289 // Is the variable found?
290 if ($found !== false) {
292 $content = $this->getVariableValue($variableGroup, $found);
295 // Return the current position
296 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
301 * Add a variable to the stack
303 * @param $variableName Name of variable to add
304 * @param $value Value we want to store in the variable
307 private function addVariable (string $variableName, $value) {
308 // Set general variable group
309 $this->setVariableGroup('general');
311 // Add it to the stack
312 $this->addGroupVariable($variableName, $value);
316 * Returns all variables of current group or empty array
318 * @return $result Whether array of found variables or empty array
320 private function readCurrentGroup () {
321 // Default is not found
324 // Is the group there?
325 if ($this->isVarStackSet($this->currGroup)) {
327 $result = $this->getVarStack($this->currGroup);
335 * Settter for variable group
337 * @param $groupName Name of variable group
338 * @param $add Whether add this group
341 public function setVariableGroup (string $groupName, bool $add = true) {
343 //* DEBIG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
344 $this->currGroup = $groupName;
346 // Skip group 'general'
347 if (($groupName != 'general') && ($add === true)) {
348 $this->variableGroups[$groupName] = 'OK';
354 * Adds a variable to current group
356 * @param $variableName Variable to set
357 * @param $value Value to store in variable
360 public function addGroupVariable (string $variableName, $value) {
361 // Replace all dashes to underscores to match variables with configuration entries
362 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
365 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
367 // Get current variables in group
368 $currVars = $this->readCurrentGroup();
370 // Append our variable
371 array_push($currVars, $this->generateVariableArray($variableName, $value));
373 // Add it to the stack
374 $this->setVarStack($this->currGroup, $currVars);
378 * Getter for variable value, throws a NoVariableException if the variable is not found
380 * @param $variableGroup Variable group to use
381 * @param $index Index in variable array
382 * @return $value Value to set
384 private function getVariableValue (string $variableGroup, int $index) {
386 return $this->varStack[$variableGroup][$index]['value'];
390 * Modify an entry on the stack
392 * @param $variableName The variable we are looking for
393 * @param $value The value we want to store in the variable
395 * @throws NoVariableException If the given variable is not found
397 private function modifyVariable (string $variableName, $value) {
398 // Replace all dashes to underscores to match variables with configuration entries
399 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
401 // Get index for variable
402 $index = $this->getVariableIndex($variableName);
404 // Is the variable set?
405 if ($index === false) {
406 // Unset variables cannot be modified
407 throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
411 $this->setVariableValue($this->currGroup, $index, $value);
415 * Sets a variable value for given variable group and index
417 * @param $variableGroup Variable group to use
418 * @param $index Index in variable array
419 * @param $value Value to set
422 private function setVariableValue (string $variableGroup, int $index, $value) {
423 $this->varStack[$variableGroup][$index]['value'] = $value;
427 * Sets a variable within given group. This method does detect if the
428 * variable is already set. If so, the variable got modified, otherwise
431 * @param $variableGroup Variable group to use
432 * @param $variableName Variable to set
433 * @param $value Value to set
436 protected function setVariable (string $variableGroup, string $variableName, $value) {
437 // Replace all dashes to underscores to match variables with configuration entries
438 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
440 // Get index for variable
441 $index = $this->getVariableIndex($variableName);
443 // Is the variable set?
444 if ($index === false) {
445 // Is the stack there?
446 if (!isset($this->varStack[$variableGroup])) {
447 // Then initialize it here
448 $this->varStack[$variableGroup] = [];
452 array_push($this->varStack[$variableGroup], $this->generateVariableArray($variableName, $value));
455 $this->setVariableValue($this->currGroup, $index, $value);
460 * "Generates" (better returns) an array for all variables for given
461 * variable/value pay.
463 * @param $variableName Variable to set
464 * @param $value Value to set
465 * @return $varData Variable data array
467 private function generateVariableArray (string $variableName, $value) {
468 // Replace all dashes to underscores to match variables with configuration entries
469 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
471 // Generate the temporary array
473 'name' => $variableName,
482 * Setter for template type. Only 'html', 'emails' and 'compiled' should
485 * @param $templateType The current template's type
488 protected final function setTemplateType (string $templateType) {
489 $this->templateType = $templateType;
493 * Getter for template type
495 * @return $templateType The current template's type
497 public final function getTemplateType () {
498 return $this->templateType;
502 * Setter for the last loaded template's file instance
504 * @param $template The last loaded template
507 private final function setLastTemplate (SplFileInfo $fileInstance) {
508 $this->lastTemplate = $fileInstance;
512 * Getter for the last loaded template's file instance
514 * @return $template The last loaded template
516 private final function getLastTemplate () {
517 return $this->lastTemplate;
521 * Setter for base path
523 * @param $templateBasePath The relative base path for all templates
526 protected final function setTemplateBasePath (string $templateBasePath) {
528 $this->templateBasePath = $templateBasePath;
532 * Getter for base path
534 * @return $templateBasePath The relative base path for all templates
536 public final function getTemplateBasePath () {
538 return $this->templateBasePath;
542 * Getter for generic base path
544 * @return $templateBasePath The relative base path for all templates
546 public final function getGenericBasePath () {
548 return $this->genericBasePath;
552 * Setter for template extension
554 * @param $templateExtension The file extension for all uncompiled
558 protected final function setRawTemplateExtension (string $templateExtension) {
560 $this->templateExtension = $templateExtension;
564 * Setter for code template extension
566 * @param $codeExtension The file extension for all uncompiled
570 protected final function setCodeTemplateExtension (string $codeExtension) {
572 $this->codeExtension = $codeExtension;
576 * Getter for template extension
578 * @return $templateExtension The file extension for all uncompiled
581 public final function getRawTemplateExtension () {
583 return $this->templateExtension;
587 * Getter for code-template extension
589 * @return $codeExtension The file extension for all code-
592 public final function getCodeTemplateExtension () {
594 return $this->codeExtension;
598 * Setter for path of compiled templates
600 * @param $compileOutputPath The local base path for all compiled
604 protected final function setCompileOutputPath (string $compileOutputPath) {
606 $this->compileOutputPath = $compileOutputPath;
610 * Unsets the given offset in the variable group
612 * @param $index Index to unset
613 * @param $variableGroup Variable group (default: currGroup)
616 protected final function unsetVariableStackOffset (int $index, string $variableGroup = NULL) {
617 // Is the variable group not set?
618 if (is_null($variableGroup)) {
619 // Then set it to current
620 $variableGroup = $this->currGroup;
623 // Is the entry there?
624 if (!isset($this->varStack[$variableGroup][$index])) {
625 // Abort here, we need fixing!
626 $this->debugInstance();
630 unset($this->varStack[$variableGroup][$index]);
634 * Private setter for raw template data
636 * @param $rawTemplateData The raw data from the template
639 protected final function setRawTemplateData (string $rawTemplateData) {
640 // And store it in this class
641 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
642 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
643 $this->rawTemplateData = $rawTemplateData;
647 * Getter for raw template data
649 * @return $rawTemplateData The raw data from the template
651 public final function getRawTemplateData () {
652 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: ' . strlen($this->rawTemplateData) . ' Bytes read.');
653 return $this->rawTemplateData;
657 * Private setter for compiled templates
659 * @param $compiledData Compiled template data
662 private final function setCompiledData (string $compiledData) {
663 // And store it in this class
664 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: ' . strlen($compiledData) . ' Bytes set.');
665 $this->compiledData = $compiledData;
669 * Getter for compiled templates, must be public for e.g. Mailer classes.
671 * @return $compiledData Compiled template data
673 public final function getCompiledData () {
674 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: ' . strlen($this->compiledData) . ' Bytes read.');
675 return $this->compiledData;
679 * Private loader for all template types
681 * @param $templateName The template we shall load
682 * @param $extOther An other extension to use
684 * @throws FileNotFoundException If the template was not found
686 protected function loadTemplate (string $templateName, string $extOther = '') {
687 // Get extension for the template if empty
688 if (empty($extOther)) {
689 // None provided, so get the raw one
690 $ext = $this->getRawTemplateExtension();
697 * Construct the FQFN for the template without language as language is
698 * now entirely done by php_intl. These old thing with language-based
699 * template paths comes from an older time.
701 $fileInstance = new SplFileInfo(sprintf('%s%s%s%s%s%s',
702 $this->getTemplateBasePath(),
703 $this->getGenericBasePath(),
704 $this->getTemplateType(),
706 (string) $templateName,
712 // Load the raw template data
713 $this->loadRawTemplateData($fileInstance);
714 } catch (FileNotFoundException $e) {
715 // If we shall load a code-template we need to switch the file extension
716 if (($this->getTemplateType() != FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('html_template_type')) && (empty($extOther))) {
717 // Switch over to the code-template extension and try it again
718 $ext = $this->getCodeTemplateExtension();
721 $this->loadTemplate($templateName, $ext);
724 throw new FileNotFoundException($fileInstance, self::EXCEPTION_FILE_NOT_FOUND);
731 * A private loader for raw template names
733 * @param $fileInstance An instance of a SplFileInfo class
736 private function loadRawTemplateData (SplFileInfo $fileInstance) {
737 // Load the raw template
738 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: fileInstance=' . $fileInstance);
739 $rawTemplateData = $this->getFileIoInstance()->loadFileContents($fileInstance);
741 // Store the template's contents into this class
742 $this->setRawTemplateData($rawTemplateData);
744 // Remember the template's file instance
745 $this->setLastTemplate($fileInstance);
749 * Try to assign an extracted template variable as a "content" or 'config'
752 * @param $variableName The variable's name (shall be content or config)
754 * @param $variableName The variable we want to assign
757 private function assignTemplateVariable (string $variableName, $var) {
758 // Replace all dashes to underscores to match variables with configuration entries
759 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: variableName=' . $variableName . ',var=' . $var);
760 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
762 // Is it not a config variable?
763 if ($variableName != 'config') {
764 // Regular template variables
765 $this->assignVariable($variableName, '');
767 // Configuration variables
768 $this->assignConfigVariable($var);
773 * Extract variables from a given raw data stream
775 * @param $rawData The raw template data we shall analyze
778 private function extractVariablesFromRawData (string $rawData) {
779 // Search for variables
780 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, true));
781 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
783 // Did we find some variables?
784 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
785 // Initialize all missing variables
786 foreach ($variableMatches[3] as $key => $var) {
788 $variableName = $variableMatches[1][$key];
790 // Workarround: Do not assign empty variables
792 // Try to assign it, empty strings are being ignored
793 $this->assignTemplateVariable($variableName, $var);
800 * Main analysis of the loaded template
802 * @param $templateMatches Found template place-holders, see below
805 *---------------------------------
806 * Structure of $templateMatches:
807 *---------------------------------
808 * [0] => Array - An array with all full matches
809 * [1] => Array - An array with left part (before the ':') of a match
810 * [2] => Array - An array with right part of a match including ':'
811 * [3] => Array - An array with right part of a match excluding ':'
813 private function analyzeTemplate (array $templateMatches) {
814 // Backup raw template data
815 $backup = $this->getRawTemplateData();
817 // Initialize some arrays
818 if (is_null($this->loadedRawData)) {
820 $this->loadedRawData = [];
821 $this->rawTemplates = [];
824 // Load all requested templates
825 foreach ($templateMatches[1] as $template) {
826 // Load and compile only templates which we have not yet loaded
827 // RECURSIVE PROTECTION! BE CAREFUL HERE!
828 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
830 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:template=' . $template);
832 // Template not found, but maybe variable assigned?
833 if ($this->getVariableIndex($template) !== false) {
834 // Use that content here
835 $this->loadedRawData[$template] = $this->readVariable($template);
837 // Recursive protection:
838 array_push($this->loadedTemplates, $template);
840 // Then try to search for code-templates
842 // Load the code template and remember it's contents
843 $this->loadCodeTemplate($template);
844 $this->loadedRawData[$template] = $this->getRawTemplateData();
846 // Remember this template for recursion detection
847 // RECURSIVE PROTECTION!
848 array_push($this->loadedTemplates, $template);
849 } catch (FileNotFoundException $e) {
850 // Even this is not done... :/
851 array_push($this->rawTemplates, $template);
857 // Restore the raw template data
858 $this->setRawTemplateData($backup);
862 * Compile a given raw template code and remember it for later usage
864 * @param $code The raw template code
865 * @param $template The template's name
868 private function compileCode (string $code, string $template) {
869 // Is this template already compiled?
870 if (in_array($template, $this->compiledTemplates)) {
875 // Remember this template being compiled
876 array_push($this->compiledTemplates, $template);
878 // Compile the loaded code in five steps:
880 // 1. Backup current template data
881 $backup = $this->getRawTemplateData();
883 // 2. Set the current template's raw data as the new content
884 $this->setRawTemplateData($code);
886 // 3. Compile the template data
887 $this->compileTemplate();
889 // 4. Remember it's contents
890 $this->loadedRawData[$template] = $this->getRawTemplateData();
892 // 5. Restore the previous raw content from backup variable
893 $this->setRawTemplateData($backup);
897 * Insert all given and loaded templates by running through all loaded
898 * codes and searching for their place-holder in the main template
900 * @param $templateMatches See method analyzeTemplate()
903 private function insertAllTemplates (array $templateMatches) {
904 // Run through all loaded codes
905 foreach ($this->loadedRawData as $template => $code) {
907 // Search for the template
908 $foundIndex = array_search($template, $templateMatches[1]);
910 // Lookup the matching template replacement
911 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
913 // Get the current raw template
914 $rawData = $this->getRawTemplateData();
916 // Replace the space holder with the template code
917 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
919 // Set the new raw data
920 $this->setRawTemplateData($rawData);
926 * Load all extra raw templates
930 private function loadExtraRawTemplates () {
931 // Are there some raw templates we need to load?
932 if (count($this->rawTemplates) > 0) {
933 // Try to load all raw templates
934 foreach ($this->rawTemplates as $key => $template) {
937 $this->loadHtmlTemplate($template);
939 // Remember it's contents
940 $this->rawTemplates[$template] = $this->getRawTemplateData();
942 // Remove it from the loader list
943 unset($this->rawTemplates[$key]);
945 // Remember this template for recursion detection
946 // RECURSIVE PROTECTION!
947 array_push($this->loadedTemplates, $template);
948 } catch (FileNotFoundException $e) {
949 // This template was never found. We silently ignore it
950 unset($this->rawTemplates[$key]);
957 * Assign all found template variables
959 * @param $varMatches An array full of variable/value pairs.
961 * @todo Unfinished work or don't die here.
963 private function assignAllVariables (array $varMatches) {
965 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:varMatches()=' . count($varMatches));
967 // Search for all variables
968 foreach ($varMatches[1] as $key => $var) {
969 // Replace all dashes to underscores to match variables with configuration entries
970 $var = trim(StringUtils::convertDashesToUnderscores($var));
973 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:key=' . $key . ',var=' . $var);
975 // Detect leading equals
976 if (substr($varMatches[2][$key], 0, 1) == '=') {
977 // Remove and cast it
978 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
981 // Do we have some quotes left and right side? Then it is free text
982 if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
983 // Free string detected! Which we can assign directly
984 $this->assignVariable($var, $varMatches[3][$key]);
985 } elseif (!empty($varMatches[2][$key])) {
986 // @TODO Non-string found so we need some deeper analysis...
987 ApplicationEntryPoint::exitApplication('Deeper analysis not yet implemented!');
993 * Compiles all loaded raw templates
995 * @param $templateMatches See method analyzeTemplate() for details
998 private function compileRawTemplateData (array $templateMatches) {
1000 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:loadedRawData()= ' .count($this->loadedRawData));
1002 // Are some code-templates found which we need to compile?
1003 if (count($this->loadedRawData) > 0) {
1004 // Then compile all!
1005 foreach ($this->loadedRawData as $template => $code) {
1007 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1009 // Is this template already compiled?
1010 if (in_array($template, $this->compiledTemplates)) {
1012 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: Template ' . $template . ' already compiled. SKIPPED!');
1016 // Search for the template
1017 $foundIndex = array_search($template, $templateMatches[1]);
1019 // Lookup the matching variable data
1020 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
1021 // Split it up with another reg. exp. into variable=value pairs
1022 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1023 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:varMatches=' . print_r($varMatches, true));
1025 // Assign all variables
1026 $this->assignAllVariables($varMatches);
1029 // Compile the loaded template
1030 $this->compileCode($code, $template);
1033 // Insert all templates
1034 $this->insertAllTemplates($templateMatches);
1039 * Inserts all raw templates into their respective variables
1043 private function insertRawTemplates () {
1044 // Load all templates
1045 foreach ($this->rawTemplates as $template => $content) {
1046 // Set the template as a variable with the content
1047 $this->assignVariable($template, $content);
1052 * Finalizes the compilation of all template variables
1056 private function finalizeVariableCompilation () {
1058 $content = $this->getRawTemplateData();
1059 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: content before=' . strlen($content) . ' (' . md5($content) . ')');
1061 // Do we have the stack?
1062 if (!$this->isVarStackSet('general')) {
1063 // Abort here silently
1064 // @TODO This silent abort should be logged, maybe.
1068 // Walk through all variables
1069 foreach ($this->getVarStack('general') as $currEntry) {
1070 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1071 // Replace all [$var] or {?$var?} with the content
1072 // @TODO Old behaviour, will become obsolete!
1073 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1075 // @TODO Yet another old way
1076 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1078 // The new behaviour
1079 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1082 // Set the content back
1083 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: content after=' . strlen($content) . ' (' . md5($content) . ')');
1084 $this->setRawTemplateData($content);
1088 * Load a specified HTML template into the engine
1090 * @param $template The web template we shall load which is located in
1094 public function loadHtmlTemplate (string $template) {
1095 // Set template type
1096 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('html_template_type'));
1098 // Load the special template
1099 $this->loadTemplate($template);
1103 * Assign (add) a given variable with a value
1105 * @param $variableName The variable we are looking for
1106 * @param $value The value we want to store in the variable
1108 * @throws InvalidArgumentException If the variable name is left empty
1110 public final function assignVariable (string $variableName, $value) {
1111 // Validate parameter
1112 if (empty($variableName)) {
1113 // Throw an exception
1114 throw new InvalidArgumentException('Parameter "variableName" is empty');
1117 // Replace all dashes to underscores to match variables with configuration entries
1118 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
1120 // First search for the variable if it was already added
1121 $index = $this->getVariableIndex($variableName);
1124 if ($index === false) {
1125 // Add it to the stack
1126 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1127 $this->addVariable($variableName, $value);
1128 } elseif (!empty($value)) {
1129 // Modify the stack entry
1130 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1131 $this->modifyVariable($variableName, $value);
1136 * Removes a given variable
1138 * @param $variableName The variable we are looking for
1139 * @param $variableGroup Name of variable group (default: 'general')
1142 public final function removeVariable (string $variableName, string $variableGroup = 'general') {
1143 // First search for the variable if it was already added
1144 $index = $this->getVariableIndex($variableName, $variableGroup);
1147 if ($index !== false) {
1148 // Remove this variable
1149 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1150 $this->unsetVariableStackOffset($index, $variableGroup);
1155 * Assigns the last loaded raw template content with a given variable
1157 * @param $templateName Name of the template we want to assign
1158 * @param $variableName Name of the variable we want to assign
1161 public function assignTemplateWithVariable (string $templateName, string $variableName) {
1162 // Get the content from last loaded raw template
1163 $content = $this->getRawTemplateData();
1165 // Assign the variable
1166 $this->assignVariable($variableName, $content);
1168 // Purge raw content
1169 $this->setRawTemplateData('');
1173 * Assign a given congfiguration variable with a value
1175 * @param $variableName The configuration variable we want to assign
1178 public function assignConfigVariable (string $variableName) {
1179 // Replace all dashes to underscores to match variables with configuration entries
1180 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
1182 // Sweet and simple...
1183 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: variableName=' . $variableName . ',getConfigEntry()=' . FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($variableName));
1184 $this->assignVariable($variableName, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($variableName));
1188 * Assigns a lot variables into the stack of currently loaded template.
1189 * This method should only be used in very rare circumstances, e.g. when
1190 * you have to copy a whole set of variables into the template engine.
1191 * Before you use this method, please make sure you have considered all
1192 * other possiblities.
1194 * @param $variables An array with variables to be assigned
1197 public function assignMultipleVariables (array $variables) {
1199 foreach ($variables as $name => $value) {
1200 // Set variable with name for 'config' group
1201 $this->assignVariable($name, $value);
1206 * Assigns all the application data with template variables
1210 public function assignApplicationData () {
1211 // Get application instance
1212 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1214 // Get long name and assign it
1215 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1217 // Get short name and assign it
1218 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1220 // Get version number and assign it
1221 $this->assignVariable('app_version' , $applicationInstance->getAppVersion());
1223 // Assign extra application-depending data
1224 $applicationInstance->assignExtraTemplateData($this);
1228 * Load a specified code template into the engine
1230 * @param $template The code template we shall load which is
1231 * located in 'code' by default
1234 public function loadCodeTemplate (string $template) {
1235 // Set template type
1236 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type'));
1238 // Load the special template
1239 $this->loadTemplate($template);
1243 * Load a specified email template into the engine
1245 * @param $template The email template we shall load which is
1246 * located in 'emails' by default
1249 public function loadEmailTemplate (string $template) {
1250 // Set template type
1251 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('email_template_type'));
1253 // Load the special template
1254 $this->loadTemplate($template);
1258 * Compiles configuration place-holders in all variables. This 'walks'
1259 * through the variable group 'general'. It interprets all values from that
1260 * variables as configuration entries after compiling them.
1264 public final function compileConfigInVariables () {
1265 // Do we have the stack?
1266 if (!$this->isVarStackSet('general')) {
1267 // Abort here silently
1268 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: Aborted, variable stack general not found!');
1272 // Iterate through all general variables
1273 foreach ($this->getVarStack('general') as $index => $currVariable) {
1274 // Compile the value
1275 $value = $this->compileRawCode($this->readVariable($currVariable['name']), true);
1278 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: name=' . $currVariable['name'] . ',value=' . $value);
1280 // Remove it from stack
1281 $this->removeVariable($currVariable['name'], 'general');
1282 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1284 // Is it a configuration key?
1285 if (FrameworkBootstrap::getConfigurationInstance()->isConfigurationEntrySet($value)) {
1286 // The value itself is a configuration entry
1287 $this->assignConfigVariable($value);
1289 // Re-assign the value directly
1290 $this->assignVariable($currVariable['name'], $value);
1296 * Compile all variables by inserting their respective values
1299 * @todo Make this code some nicer...
1301 public final function compileVariables () {
1302 // Initialize the $content array
1303 $validVar = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('tpl_valid_var');
1306 // Iterate through all general variables
1307 foreach ($this->getVarStack('general') as $currVariable) {
1308 // Transfer it's name/value combination to the $content array
1309 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1310 $dummy[$currVariable['name']] = $currVariable['value'];
1313 // Set the new variable (don't remove the second dollar!)
1314 $$validVar = $dummy;
1316 // Remove some variables
1318 unset($currVariable);
1320 // Run the compilation three times to get content from helper classes in
1323 // Finalize the compilation of template variables
1324 $this->finalizeVariableCompilation();
1326 // Prepare the eval() command for comiling the template
1327 $eval = sprintf('$result = "%s";',
1328 addslashes($this->getRawTemplateData())
1331 // This loop does remove the backslashes (\) in PHP parameters
1332 while (strpos($eval, $this->codeBegin) !== false) {
1333 // Get left part before "<?"
1334 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1336 // Get all from right of "<?"
1337 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1339 // Cut middle part out and remove escapes
1340 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1341 $evalMiddle = stripslashes($evalMiddle);
1343 // Remove the middle part from right one
1344 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1346 // And put all together
1347 $eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
1350 // Prepare PHP code for eval() command
1351 $eval = str_replace(
1360 // Run the constructed command. This will "compile" all variables in
1363 // Goes something wrong?
1364 if ((!isset($result)) || (empty($result))) {
1365 // Output eval command
1366 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Failed eval() code: <pre>%s</pre>', $this->markupCode($eval, true)), true);
1368 // Output backtrace here
1369 $this->debugBackTrace();
1372 // Set raw template data
1373 $this->setRawTemplateData($result);
1377 // Final variable assignment
1378 $this->finalizeVariableCompilation();
1380 // Set the new content
1381 $this->setCompiledData($this->getRawTemplateData());
1385 * Compile all required templates into the current loaded one
1388 * @throws UnexpectedTemplateTypeException If the template type is
1390 * @throws InvalidArrayCountException If an unexpected array
1391 * count has been found
1393 public function compileTemplate () {
1394 // Get code type to make things shorter
1395 $codeType = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type');
1397 // We will only work with template type "code" from configuration
1398 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1400 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1403 // Get the raw data.
1404 $rawData = $this->getRawTemplateData();
1406 // Remove double spaces and trim leading/trailing spaces
1407 $rawData = trim(str_replace(' ', ' ', $rawData));
1409 // Search for raw variables
1410 $this->extractVariablesFromRawData($rawData);
1412 // Search for code-tags which are {? ?}
1413 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1416 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:templateMatches=' . print_r($templateMatches , true));
1418 // Analyze the matches array
1419 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1420 // Entries are found:
1422 // The main analysis
1423 $this->analyzeTemplate($templateMatches);
1425 // Compile raw template data
1426 $this->compileRawTemplateData($templateMatches);
1428 // Are there some raw templates left for loading?
1429 $this->loadExtraRawTemplates();
1431 // Are some raw templates found and loaded?
1432 if (count($this->rawTemplates) > 0) {
1433 // Insert all raw templates
1434 $this->insertRawTemplates();
1436 // Remove the raw template content as well
1437 $this->setRawTemplateData('');
1443 * Loads a given view helper (by name)
1445 * @param $helperName The helper's name
1448 protected function loadViewHelper (string $helperName) {
1449 // Is this view helper loaded?
1450 if (!isset($this->helpers[$helperName])) {
1451 // Create a class name
1452 $className = StringUtils::convertToClassName($helperName) . 'ViewHelper';
1454 // Generate new instance
1455 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1458 // Return the requested instance
1459 return $this->helpers[$helperName];
1463 * Transfers the content of this template engine to a given response instance
1465 * @param $responseInstance An instance of a Responseable class
1468 public function transferToResponse (Responseable $responseInstance) {
1469 // Get the content and set it in response class
1470 $responseInstance->writeToBody($this->getCompiledData());
1474 * "Compiles" a variable by replacing {?var?} with it's content
1476 * @param $rawCode Raw code to compile
1477 * @param $setMatchAsCode Sets $match if readVariable() returns empty result
1478 * @return $rawCode Compile code with inserted variable value
1480 public function compileRawCode (string $rawCode, bool $setMatchAsCode = false) {
1481 // Find the variables
1482 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1483 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1485 // Compile all variables
1486 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:<pre>' . print_r($varMatches, true) . '</pre>');
1487 foreach ($varMatches[0] as $match) {
1488 // Add variable tags around it
1489 $varCode = '{?' . $match . '?}';
1492 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:varCode=' . $varCode);
1494 // Is the variable found in code? (safes some calls)
1495 if (strpos($rawCode, $varCode) !== false) {
1497 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
1499 // Use $match as new value or $value from read variable?
1500 if ($setMatchAsCode === true) {
1502 $rawCode = str_replace($varCode, $match, $rawCode);
1504 // Read the variable
1505 $value = $this->readVariable($match);
1508 $rawCode = str_replace($varCode, $value, $rawCode);
1513 // Return the compiled data
1514 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1519 * Getter for variable group array
1521 * @return $variableGroups All variable groups
1523 public final function getVariableGroups () {
1524 return $this->variableGroups;
1528 * Renames a variable in code and in stack
1530 * @param $oldName Old name of variable
1531 * @param $newName New name of variable
1534 public function renameVariable (string $oldName, string $newName) {
1535 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: oldName=' . $oldName . ', newName=' . $newName);
1536 // Get raw template code
1537 $rawData = $this->getRawTemplateData();
1540 $rawData = str_replace($oldName, $newName, $rawData);
1542 // Set the code back
1543 $this->setRawTemplateData($rawData);
1547 * Enables or disables language support
1549 * @param $languageSupport New language support setting
1552 public final function enableLanguageSupport (bool $languageSupport = true) {
1553 $this->languageSupport = $languageSupport;
1557 * Checks whether language support is enabled
1559 * @return $languageSupport Whether language support is enabled or disabled
1561 public final function isLanguageSupportEnabled () {
1562 return $this->languageSupport;
1566 * Removes all commentd, tabs and new-line characters to compact the content
1568 * @param $uncompactedContent The uncompacted content
1569 * @return $compactedContent The compacted content
1571 public function compactContent (string $uncompactedContent) {
1572 // First, remove all tab/new-line/revert characters
1573 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
1575 // Then regex all comments like <!-- //--> away
1576 preg_match_all($this->regExpComments, $compactedContent, $matches);
1578 // Do we have entries?
1579 if (isset($matches[0][0])) {
1581 foreach ($matches[0] as $match) {
1583 $compactedContent = str_replace($match, '', $compactedContent);
1587 // Set the content again
1588 $this->setRawTemplateData($compactedContent);
1590 // Return compacted content
1591 return $compactedContent;