]> 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\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\String\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          * Protected constructor
91          *
92          * @param       $className      Name of the class
93          * @return      void
94          */
95         protected function __construct (string $className) {
96                 // Call parent constructor
97                 parent::__construct($className);
98         }
99
100         /**
101          * Does a generic initialization of the template engine
102          *
103          * @param       $typePrefix                             Type prefix
104          * @param       $xmlTemplateType                Type of XML template
105          * @return      $templateInstance               An instance of TemplateEngine
106          * @throws      BasePathIsEmptyException                If the provided $templateBasePath is empty
107          * @throws      InvalidBasePathStringException  If $templateBasePath is no string
108          * @throws      BasePathIsNoDirectoryException  If $templateBasePath is no
109          *                                                                                      directory or not found
110          * @throws      BasePathReadProtectedException  If $templateBasePath is
111          *                                                                                      read-protected
112          */
113         protected function initXmlTemplateEngine (string $typePrefix, string $xmlTemplateType) {
114                 // Set XML template type and prefix
115                 $this->xmlTemplateType = $xmlTemplateType;
116                 $this->typePrefix      = $typePrefix;
117
118                 // Get template instance
119                 $applicationInstance = ApplicationHelper::getSelfInstance();
120
121                 // Determine base path
122                 $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . FrameworkBootstrap::getRequestInstance()->getRequestElement('app') . '/';
123
124                 // Is the base path valid?
125                 if (empty($templateBasePath)) {
126                         // Base path is empty
127                         throw new BasePathIsEmptyException($this, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
128                 } elseif (!is_dir($templateBasePath)) {
129                         // Is not a path
130                         throw new BasePathIsNoDirectoryException(array($this, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
131                 } elseif (!is_readable($templateBasePath)) {
132                         // Is not readable
133                         throw new BasePathReadProtectedException(array($this, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
134                 }
135
136                 // Set the base path
137                 $this->setTemplateBasePath($templateBasePath);
138
139                 // Set template extensions
140                 $this->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
141                 $this->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($typePrefix . '_message_template_extension'));
142
143                 // Absolute output path for compiled templates
144                 $this->setCompileOutputPath(sprintf('%s%s',
145                         $templateBasePath,
146                         FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
147                 ));
148
149                 // Init a variable stacker
150                 $stackInstance = ObjectFactory::createObjectByConfiguredName($typePrefix . '_' . $xmlTemplateType . '_stacker_class');
151
152                 // Set name
153                 $this->stackerName = $typePrefix . '_' . $xmlTemplateType;
154
155                 // Init stacker
156                 $stackInstance->initStack($this->stackerName);
157
158                 // Set it
159                 $this->setStackInstance($stackInstance);
160
161                 // Set it in main nodes
162                 array_push($this->mainNodes, str_replace('_', '-', $xmlTemplateType));
163         }
164
165         /**
166          * Load a specified XML template into the engine
167          *
168          * @param       $templateName   Optional name of template
169          * @return      void
170          */
171         public function loadXmlTemplate (string $templateName = '') {
172                 // Is the template name empty?
173                 if (empty($templateName)) {
174                         // Set generic template name
175                         $templateName = $this->typePrefix . '_' . $this->xmlTemplateType . '_template_type';
176                 } // END - if
177
178                 // Set template type
179                 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($templateName));
180
181                 // Load the special template
182                 $this->loadTemplate($this->xmlTemplateType);
183         }
184
185         /**
186          * Getter for current main node
187          *
188          * @return      $currMainNode   Current main node
189          */
190         public final function getCurrMainNode () {
191                 return $this->curr['main_node'];
192         }
193
194         /**
195          * Setter for current main node
196          *
197          * @param       $element                Element name to set as current main node
198          * @return      $currMainNode   Current main node
199          */
200         private final function setCurrMainNode (string $element) {
201                 $this->curr['main_node'] = $element;
202         }
203
204         /**
205          * Getter for main node array
206          *
207          * @return      $mainNodes      Array with valid main node names
208          */
209         public final function getMainNodes () {
210                 return $this->mainNodes;
211         }
212
213         /**
214          * Getter for stacker name
215          *
216          * @return      $stackerName    Name of stacker of this class
217          */
218         protected final function getStackerName () {
219                 return $this->stackerName;
220         }
221
222         /**
223          * Setter for sub node array
224          *
225          * @param       $subNodes       Array with valid sub node names
226          * @return      void
227          */
228         public final function setSubNodes (array $subNodes) {
229                 $this->subNodes = $subNodes;
230         }
231
232         /**
233          * Getter for sub node array
234          *
235          * @return      $subNodes       Array with valid sub node names
236          */
237         public final function getSubNodes () {
238                 return $this->subNodes;
239         }
240
241         /**
242          * Read XML variables by calling readVariable() with 'general' as
243          * variable stack.
244          *
245          * @param       $key    Key to read from
246          * @return      $value  Value from variable
247          */
248         public function readXmlData (string $key) {
249                 // Is key parameter valid?
250                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: key=%s - CALLED!', $key));
251                 if (empty($key)) {
252                         // Throw exception
253                         throw new InvalidArgumentException('Parameter key is empty');
254                 }
255
256                 // Read the variable
257                 $value = parent::readVariable($key, 'general');
258
259                 // Is this null?
260                 if (is_null($value)) {
261                         // Bah, needs fixing.
262                         $this->debugInstance(sprintf('[%s:%d]: key=%s returns NULL', __METHOD__, __LINE__, $key));
263                 } // END - if
264
265                 // Return value
266                 return $value;
267         }
268
269         /**
270          * Handles the template dependency for given XML node
271          *
272          * @param       $node                                   The XML node we should load a dependency template
273          * @param       $templateDependency             A template to load to satisfy dependencies
274          * @return      void
275          */
276         protected function handleTemplateDependency (string $node, string $templateDependency) {
277                 // Check that the XML node is not empty
278                 assert(!empty($node));
279
280                 // Is the template dependency set?
281                 if ((!empty($templateDependency)) && (!isset($this->dependencyContent[$node]))) {
282                         // Get a temporay template instance
283                         $templateInstance = XmlTemplateEngineFactory::createXmlTemplateEngineInstance($this->typePrefix . '_' . self::convertDashesToUnderscores($node) . '_' . $this->xmlTemplateType . '_template_class');
284
285                         // Then load it
286                         $templateInstance->loadXmlTemplate($templateDependency);
287
288                         // Parse the XML content
289                         $templateInstance->renderXmlContent();
290
291                         // Save the parsed raw content in our dependency array
292                         $this->dependencyContent[$node] = $templateInstance->getRawTemplateData();
293                 } // END - if
294         }
295
296         /**
297          * Handles the start element of an XML resource
298          *
299          * @param       $resource               XML parser resource (currently ignored)
300          * @param       $element                The element we shall handle
301          * @param       $attributes             All attributes
302          * @return      void
303          * @throws      InvalidXmlNodeException         If an unknown/invalid XML node name was found
304          */
305         public final function startElement ($resource, string $element, array $attributes) {
306                 // Initial method name which will never be called...
307                 $methodName = 'init' . StringUtils::convertToClassName($this->xmlTemplateType);
308
309                 // Make the element name lower-case
310                 $element = strtolower($element);
311
312                 // Is the element a main node?
313                 //* DEBUG: */ echo "START: &gt;".$element."&lt;<br />\n";
314                 if (in_array($element, $this->getMainNodes())) {
315                         // Okay, main node found!
316                         $methodName = 'start' . StringUtils::convertToClassName($element);
317
318                         // Set it
319                         $this->setCurrMainNode($element);
320                 } elseif (in_array($element, $this->getSubNodes())) {
321                         // Sub node found
322                         $methodName = 'start' . StringUtils::convertToClassName($element);
323                 } else {
324                         // Invalid node name found
325                         throw new InvalidXmlNodeException(array($this, $element, $attributes), XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
326                 }
327
328                 // Call method
329                 call_user_func_array(array($this, $methodName), $attributes);
330         }
331
332         /**
333          * Ends the main or sub node by sending out the gathered data
334          *
335          * @param       $resource       An XML resource pointer (currently ignored)
336          * @param       $nodeName       Name of the node we want to finish
337          * @return      void
338          * @throws      XmlNodeMismatchException        If current main node mismatches the closing one
339          */
340         public final function finishElement ($resource, string $nodeName) {
341                 // Make all lower-case
342                 $nodeName = strtolower($nodeName);
343
344                 // Does this match with current main node?
345                 //* DEBUG: */ echo "END: &gt;".$nodeName."&lt;<br />\n";
346                 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
347                         // Did not match!
348                         throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), XmlParser::EXCEPTION_XML_NODE_MISMATCH);
349                 } // END - if
350
351                 // Construct method name
352                 $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
353
354                 // Call the corresponding method
355                 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
356                 call_user_func_array(array($this, $methodName), array());
357         }
358
359         /**
360          * Renders the given XML content
361          *
362          * @param       $content        Valid XML content or if not set the current loaded raw content
363          * @return      void
364          * @throws      XmlParserException      If an XML error was found
365          */
366         public function renderXmlContent (string $content = NULL) {
367                 // Is the content set?
368                 if (is_null($content)) {
369                         // Get current content
370                         $content = $this->getRawTemplateData();
371                 }
372
373                 // Get a XmlParser instance
374                 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', [$this]);
375
376                 // Check if XML compacting is enabled
377                 if ($this->isXmlCompactingEnabled()) {
378                         // Yes, so get a decorator class for transparent compacting
379                         $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
380                 }
381
382                 // Parse the XML document
383                 $parserInstance->parseXmlContent($content);
384         }
385
386         /**
387          * Enables or disables XML compacting
388          *
389          * @param       $xmlCompacting  New XML compacting setting
390          * @return      void
391          */
392         public final function enableXmlCompacting (bool $xmlCompacting = true) {
393                 $this->xmlCompacting = $xmlCompacting;
394         }
395
396         /**
397          * Checks whether XML compacting is enabled
398          *
399          * @return      $xmlCompacting  Whether XML compacting is enabled or disabled
400          */
401         public final function isXmlCompactingEnabled () {
402                 return $this->xmlCompacting;
403         }
404
405 }