]> git.mxchange.org Git - core.git/blob - framework/main/classes/template/xml/class_BaseXmlTemplateEngine.php
Continued:
[core.git] / framework / main / classes / template / xml / class_BaseXmlTemplateEngine.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Template\Engine\Xml;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
8 use Org\Mxchange\CoreFramework\Factory\Template\XmlTemplateEngineFactory;
9 use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
10 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
11 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
12 use Org\Mxchange\CoreFramework\Template\Engine\BaseTemplateEngine;
13 use Org\Mxchange\CoreFramework\Template\Xml\CompileableXmlTemplate;
14 use Org\Mxchange\CoreFramework\Traits\Stack\StackableTrait;
15 use Org\Mxchange\CoreFramework\Traits\Template\CompileableTemplateTrait;
16 use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
17
18 // Import SPL stuff
19 use \InvalidArgumentException;
20
21 /**
22  * A generic XML template engine class
23  *
24  * @author              Roland Haeder <webmaster@shipsimu.org>
25  * @version             0.0.0
26  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2018 Hub Developer Team
27  * @license             GNU GPL 3.0 or any newer version
28  * @link                http://www.shipsimu.org
29  * @todo                This template engine does not make use of setTemplateType()
30  *
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.
35  *
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.
40  *
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/>.
43  */
44 abstract class BaseXmlTemplateEngine extends BaseTemplateEngine implements CompileableXmlTemplate {
45         // Load traits
46         use CompileableTemplateTrait;
47         use StackableTrait;
48
49         /**
50          * Main nodes in the XML tree
51          */
52         private $mainNodes = [];
53
54         /**
55          * Sub nodes in the XML tree
56          */
57         private $subNodes = [];
58
59         /**
60          * Current main node
61          */
62         private $curr = [];
63
64         /**
65          * XML template type
66          */
67         private $xmlTemplateType = 'xml';
68
69         /**
70          * Type prefix
71          */
72         private $typePrefix = 'xml';
73
74         /**
75          * Name of stacker
76          */
77         private $stackerName = '';
78
79         /**
80          * Content from dependency
81          */
82         protected $dependencyContent = [];
83
84         /**
85          * XML compacting is disabled by default
86          */
87         private $xmlCompacting = false;
88
89         /**
90          * Method name for XML template type
91          */
92         private $initMethodName = 'invalid';
93
94         /**
95          * Protected constructor
96          *
97          * @param       $className      Name of the class
98          * @return      void
99          */
100         protected function __construct (string $className) {
101                 // Call parent constructor
102                 parent::__construct($className);
103         }
104
105         /**
106          * Does a generic initialization of the template engine
107          *
108          * @param       $typePrefix                             Type prefix
109          * @param       $xmlTemplateType                Type of XML template
110          * @return      $templateInstance               An instance of TemplateEngine
111          * @throws      BasePathIsEmptyException                If the provided $templateBasePath is empty
112          * @throws      InvalidBasePathStringException  If $templateBasePath is no string
113          * @throws      BasePathIsNoDirectoryException  If $templateBasePath is no
114          *                                                                                      directory or not found
115          * @throws      BasePathReadProtectedException  If $templateBasePath is
116          *                                                                                      read-protected
117          */
118         protected function initXmlTemplateEngine (string $typePrefix, string $xmlTemplateType) {
119                 // Set XML template type and prefix
120                 $this->xmlTemplateType = $xmlTemplateType;
121                 $this->typePrefix      = $typePrefix;
122                 $this->initMethodName = sprintf('init%s', StringUtils::convertToClassName($this->xmlTemplateType));
123
124                 // Get template instance
125                 $applicationInstance = ApplicationHelper::getSelfInstance();
126
127                 // Determine base path
128                 $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . FrameworkBootstrap::getRequestInstance()->getRequestElement('app') . '/';
129
130                 // Is the base path valid?
131                 if (empty($templateBasePath)) {
132                         // Base path is empty
133                         throw new BasePathIsEmptyException($this, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
134                 } elseif (!is_dir($templateBasePath)) {
135                         // Is not a path
136                         throw new BasePathIsNoDirectoryException(array($this, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
137                 } elseif (!is_readable($templateBasePath)) {
138                         // Is not readable
139                         throw new BasePathReadProtectedException(array($this, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
140                 }
141
142                 // Set the base path
143                 $this->setTemplateBasePath($templateBasePath);
144
145                 // Set template extensions
146                 $this->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
147                 $this->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($typePrefix . '_message_template_extension'));
148
149                 // Absolute output path for compiled templates
150                 $this->setCompileOutputPath(sprintf('%s%s',
151                         $templateBasePath,
152                         FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
153                 ));
154
155                 // Init a variable stacker
156                 $stackInstance = ObjectFactory::createObjectByConfiguredName($typePrefix . '_' . $xmlTemplateType . '_stacker_class');
157
158                 // Set name
159                 $this->stackerName = $typePrefix . '_' . $xmlTemplateType;
160
161                 // Init stacker
162                 $stackInstance->initStack($this->stackerName);
163
164                 // Set it
165                 $this->setStackInstance($stackInstance);
166
167                 // Set it in main nodes
168                 array_push($this->mainNodes, str_replace('_', '-', $xmlTemplateType));
169         }
170
171         /**
172          * Load a specified XML template into the engine
173          *
174          * @param       $templateName   Optional name of template
175          * @return      void
176          */
177         public function loadXmlTemplate (string $templateName = '') {
178                 // Is the template name empty?
179                 if (empty($templateName)) {
180                         // Set generic template name
181                         $templateName = $this->typePrefix . '_' . $this->xmlTemplateType . '_template_type';
182                 }
183
184                 // Set template type
185                 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($templateName));
186
187                 // Load the special template
188                 $this->loadTemplate($this->xmlTemplateType);
189         }
190
191         /**
192          * Getter for current main node
193          *
194          * @return      $currMainNode   Current main node
195          */
196         public final function getCurrMainNode () {
197                 return $this->curr['main_node'];
198         }
199
200         /**
201          * Setter for current main node
202          *
203          * @param       $element                Element name to set as current main node
204          * @return      $currMainNode   Current main node
205          */
206         private final function setCurrMainNode (string $element) {
207                 $this->curr['main_node'] = $element;
208         }
209
210         /**
211          * Getter for main node array
212          *
213          * @return      $mainNodes      Array with valid main node names
214          */
215         public final function getMainNodes () {
216                 return $this->mainNodes;
217         }
218
219         /**
220          * Getter for stacker name
221          *
222          * @return      $stackerName    Name of stacker of this class
223          */
224         protected final function getStackerName () {
225                 return $this->stackerName;
226         }
227
228         /**
229          * Setter for sub node array
230          *
231          * @param       $subNodes       Array with valid sub node names
232          * @return      void
233          */
234         public final function setSubNodes (array $subNodes) {
235                 $this->subNodes = $subNodes;
236         }
237
238         /**
239          * Getter for sub node array
240          *
241          * @return      $subNodes       Array with valid sub node names
242          */
243         public final function getSubNodes () {
244                 return $this->subNodes;
245         }
246
247         /**
248          * Read XML variables by calling readVariable() with 'general' as
249          * variable stack.
250          *
251          * @param       $key    Key to read from
252          * @return      $value  Value from variable
253          */
254         public function readXmlData (string $key) {
255                 // Is key parameter valid?
256                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: key=%s - CALLED!', $key));
257                 if (empty($key)) {
258                         // Throw exception
259                         throw new InvalidArgumentException('Parameter key is empty');
260                 }
261
262                 // Read the variable
263                 $value = parent::readVariable($key, 'general');
264
265                 // Is this null?
266                 if (is_null($value)) {
267                         // Bah, needs fixing.
268                         $this->debugInstance(sprintf('[%s:%d]: key=%s returns NULL', __METHOD__, __LINE__, $key));
269                 }
270
271                 // Return value
272                 return $value;
273         }
274
275         /**
276          * Handles the template dependency for given XML node
277          *
278          * @param       $node                                   The XML node we should load a dependency template
279          * @param       $templateDependency             A template to load to satisfy dependencies
280          * @return      void
281          */
282         protected function handleTemplateDependency (string $node, string $templateDependency) {
283                 // Check that the XML node is not empty
284                 assert(!empty($node));
285
286                 // Is the template dependency set?
287                 if ((!empty($templateDependency)) && (!isset($this->dependencyContent[$node]))) {
288                         // Get a temporay template instance
289                         $templateInstance = XmlTemplateEngineFactory::createXmlTemplateEngineInstance($this->typePrefix . '_' . self::convertDashesToUnderscores($node) . '_' . $this->xmlTemplateType . '_template_class');
290
291                         // Then load it
292                         $templateInstance->loadXmlTemplate($templateDependency);
293
294                         // Parse the XML content
295                         $templateInstance->renderXmlContent();
296
297                         // Save the parsed raw content in our dependency array
298                         $this->dependencyContent[$node] = $templateInstance->getRawTemplateData();
299                 }
300         }
301
302         /**
303          * Handles the start element of an XML resource
304          *
305          * @param       $resource               XML parser resource (currently ignored)
306          * @param       $element                The element we shall handle
307          * @param       $attributes             All attributes
308          * @return      void
309          * @throws      InvalidXmlNodeException         If an unknown/invalid XML node name was found
310          */
311         public final function startElement ($resource, string $element, array $attributes) {
312                 // Initial method name which will never be called...
313                 $methodName = $this->initMethodName;
314
315                 // Make the element name lower-case
316                 $element = strtolower($element);
317
318                 // Is the element a main node?
319                 //* DEBUG: */ echo "START: &gt;".$element."&lt;<br />\n";
320                 if (in_array($element, $this->getMainNodes())) {
321                         // Okay, main node found!
322                         $methodName = 'start' . StringUtils::convertToClassName($element);
323
324                         // Set it
325                         $this->setCurrMainNode($element);
326                 } elseif (in_array($element, $this->getSubNodes())) {
327                         // Sub node found
328                         $methodName = 'start' . StringUtils::convertToClassName($element);
329                 } else {
330                         // Invalid node name found
331                         throw new InvalidXmlNodeException(array($this, $element, $attributes), XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
332                 }
333
334                 // Call method
335                 call_user_func_array(array($this, $methodName), $attributes);
336         }
337
338         /**
339          * Ends the main or sub node by sending out the gathered data
340          *
341          * @param       $resource       An XML resource pointer (currently ignored)
342          * @param       $nodeName       Name of the node we want to finish
343          * @return      void
344          * @throws      XmlNodeMismatchException        If current main node mismatches the closing one
345          */
346         public final function finishElement ($resource, string $nodeName) {
347                 // Make all lower-case
348                 $nodeName = strtolower($nodeName);
349
350                 // Does this match with current main node?
351                 //* DEBUG: */ echo "END: &gt;".$nodeName."&lt;<br />\n";
352                 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
353                         // Did not match!
354                         throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), XmlParser::EXCEPTION_XML_NODE_MISMATCH);
355                 }
356
357                 // Construct method name
358                 $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
359
360                 // Call the corresponding method
361                 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
362                 call_user_func_array(array($this, $methodName), array());
363         }
364
365         /**
366          * Renders the given XML content
367          *
368          * @param       $content        Valid XML content or if not set the current loaded raw content
369          * @return      void
370          * @throws      XmlParserException      If an XML error was found
371          */
372         public function renderXmlContent (string $content = NULL) {
373                 // Is the content set?
374                 if (is_null($content)) {
375                         // Get current content
376                         $content = $this->getRawTemplateData();
377                 }
378
379                 // Get a XmlParser instance
380                 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', [$this]);
381
382                 // Check if XML compacting is enabled
383                 if ($this->isXmlCompactingEnabled()) {
384                         // Yes, so get a decorator class for transparent compacting
385                         $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
386                 }
387
388                 // Parse the XML document
389                 $parserInstance->parseXmlContent($content);
390         }
391
392         /**
393          * Enables or disables XML compacting
394          *
395          * @param       $xmlCompacting  New XML compacting setting
396          * @return      void
397          */
398         public final function enableXmlCompacting (bool $xmlCompacting = true) {
399                 $this->xmlCompacting = $xmlCompacting;
400         }
401
402         /**
403          * Checks whether XML compacting is enabled
404          *
405          * @return      $xmlCompacting  Whether XML compacting is enabled or disabled
406          */
407         public final function isXmlCompactingEnabled () {
408                 return $this->xmlCompacting;
409         }
410
411 }