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