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