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