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