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