3 namespace Org\Mxchange\CoreFramework\Template\Engine\Xml;
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;
19 use \InvalidArgumentException;
22 * A generic XML template engine class
24 * @author Roland Haeder <webmaster@shipsimu.org>
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()
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.
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.
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/>.
44 abstract class BaseXmlTemplateEngine extends BaseTemplateEngine implements CompileableXmlTemplate {
46 use CompileableTemplateTrait;
50 * Main nodes in the XML tree
52 private $mainNodes = [];
55 * Sub nodes in the XML tree
57 private $subNodes = [];
67 private $xmlTemplateType = 'xml';
72 private $typePrefix = 'xml';
77 private $stackerName = '';
80 * Content from dependency
82 protected $dependencyContent = [];
85 * XML compacting is disabled by default
87 private $xmlCompacting = false;
90 * Method name for XML template type
92 private $initMethodName = 'invalid';
95 * Protected constructor
97 * @param $className Name of the class
100 protected function __construct (string $className) {
101 // Call parent constructor
102 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: className=%s - CONSTRUCTED!', $className));
103 parent::__construct($className);
106 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!');
110 * Does a generic initialization of the template engine
112 * @param $typePrefix Type prefix
113 * @param $xmlTemplateType Type of XML template
114 * @return $templateInstance An instance of TemplateEngine
115 * @throws InvalidArgumentException If a parameter has an invalid value
116 * @throws BasePathIsEmptyException If the provided $templateBasePath is empty
117 * @throws InvalidBasePathStringException If $templateBasePath is no string
118 * @throws BasePathIsNoDirectoryException If $templateBasePath is no
119 * directory or not found
120 * @throws BasePathReadProtectedException If $templateBasePath is
123 protected function initXmlTemplateEngine (string $typePrefix, string $xmlTemplateType) {
124 // Check on parameter
125 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: typePrefix=%s,xmlTemplateType=%s - CALLED!', $typePrefix, $xmlTemplateType));
126 if (empty($typePrefix)) {
128 throw new InvalidArgumentException('Parameter "typePrefix" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
129 } elseif (empty($xmlTemplateType)) {
131 throw new InvalidArgumentException('Parameter "xmlTemplateType" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
134 // Set XML template type and prefix
135 $this->xmlTemplateType = $xmlTemplateType;
136 $this->typePrefix = $typePrefix;
137 $this->initMethodName = sprintf('init%s', StringUtils::convertToClassName($this->xmlTemplateType));
139 // Get template instance
140 $applicationInstance = ApplicationHelper::getSelfInstance();
142 // Determine base path
143 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: applicationInstance=%s', $applicationInstance->__toString()));
144 $templateBasePath = sprintf('%s%s%s',
145 FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path'),
146 FrameworkBootstrap::getRequestInstance()->getRequestElement('app'),
150 // Is the base path valid?
151 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: templateBasePath=%s', $templateBasePath));
152 if (empty($templateBasePath)) {
153 // Base path is empty
154 throw new BasePathIsEmptyException($this, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
155 } elseif (!is_dir($templateBasePath)) {
157 throw new BasePathIsNoDirectoryException(array($this, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
158 } elseif (!is_readable($templateBasePath)) {
160 throw new BasePathReadProtectedException(array($this, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
164 $this->setTemplateBasePath($templateBasePath);
166 // Set template extensions
167 $this->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
168 $this->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($typePrefix . '_message_template_extension'));
170 // Absolute output path for compiled templates
171 $this->setCompileOutputPath(sprintf('%s%s',
173 FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
176 // Init a variable stacker
177 $stackInstance = ObjectFactory::createObjectByConfiguredName($typePrefix . '_' . $xmlTemplateType . '_stacker_class');
180 $this->stackerName = $typePrefix . '_' . $xmlTemplateType;
183 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: this->stackerName=%s', $this->stackerName));
184 $stackInstance->initStack($this->stackerName);
187 $this->setStackInstance($stackInstance);
189 // Set it in main nodes
190 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Adding xmlTemplateType=%s to this->mainNodes ...', $xmlTemplateType));
191 array_push($this->mainNodes, str_replace('_', '-', $xmlTemplateType));
194 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!');
198 * Load a specified XML template into the engine
200 * @param $templateName Optional name of template
203 public function loadXmlTemplate (string $templateName = '') {
204 // Is the template name empty?
205 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: templateName=%s - CALLED!', $templateName));
206 if (empty($templateName)) {
207 // Set generic template name
208 $templateName = $this->typePrefix . '_' . $this->xmlTemplateType . '_template_type';
212 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: templateName=%s', $templateName));
213 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($templateName));
215 // Load the special template
216 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Invoking this->loadTemplate(%s) ...', $this->xmlTemplateType));
217 $this->loadTemplate($this->xmlTemplateType);
220 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!');
224 * Getter for current main node
226 * @return $currMainNode Current main node
228 public final function getCurrMainNode () {
229 return $this->curr['main_node'];
233 * Setter for current main node
235 * @param $element Element name to set as current main node
236 * @return $currMainNode Current main node
238 private final function setCurrMainNode (string $element) {
239 $this->curr['main_node'] = $element;
243 * Getter for main node array
245 * @return $mainNodes Array with valid main node names
247 public final function getMainNodes () {
248 return $this->mainNodes;
252 * Getter for stacker name
254 * @return $stackerName Name of stacker of this class
256 protected final function getStackerName () {
257 return $this->stackerName;
261 * Setter for sub node array
263 * @param $subNodes Array with valid sub node names
266 public final function setSubNodes (array $subNodes) {
267 $this->subNodes = $subNodes;
271 * Getter for sub node array
273 * @return $subNodes Array with valid sub node names
275 public final function getSubNodes () {
276 return $this->subNodes;
280 * Read XML variables by calling readVariable() with 'general' as
283 * @param $key Key to read from
284 * @return $value Value from variable
286 public function readXmlData (string $key) {
287 // Is key parameter valid?
288 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: key=%s - CALLED!', $key));
291 throw new InvalidArgumentException('Parameter key is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
295 $value = parent::readVariable($key, 'general');
298 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: value[]=%s', gettype($value)));
299 if (is_null($value)) {
300 // Bah, needs fixing.
301 $this->debugInstance(sprintf('[%s:%d]: key=%s returns NULL', __METHOD__, __LINE__, $key));
305 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: value[%s]=%s - EXIT!', gettype($value), $value));
310 * Handles the template dependency for given XML node
312 * @param $node The XML node we should load a dependency template
313 * @param $templateDependency A template to load to satisfy dependencies
315 * @throws InvalidArgumentException If a parameter has an invalid value
317 protected function handleTemplateDependency (string $node, string $templateDependency) {
319 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: node=%s,templateDependency=%s - CALLED!', $node, $templateDependency));
322 throw new InvalidArgumentException('Parameter "node" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
323 } elseif (empty($templateDependency)) {
325 throw new InvalidArgumentException('Parameter "templateDependency" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
328 // Is the template dependency set?
329 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: node=%s,templateDependency=%s', $node, $templateDependency));
330 if ((!empty($templateDependency)) && (!isset($this->dependencyContent[$node]))) {
332 $configKey = sprintf('%s_%s_%s_template_class', $this->typePrefix, self::convertDashesToUnderscores($node), $this->xmlTemplateType);
334 // Get a temporay template instance
335 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: configKey=%s', $configKey));
336 $templateInstance = XmlTemplateEngineFactory::createXmlTemplateEngineInstance();
339 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: templateInstance=%s', $templateInstance->__toString()));
340 $templateInstance->loadXmlTemplate($templateDependency);
342 // Parse the XML content
343 $templateInstance->renderXmlContent();
345 // Save the parsed raw content in our dependency array
346 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Invoking templateInstance->getRawTemplateData() for this->dependencyContent[%s] ...', $node));
347 $this->dependencyContent[$node] = $templateInstance->getRawTemplateData();
351 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!');
355 * Handles the start element of an XML resource
357 * @param $resource XML parser resource (currently ignored)
358 * @param $element The element we shall handle
359 * @param $attributes All attributes
361 * @throws InvalidArgumentException If a parameter has an invalid value
362 * @throws InvalidXmlNodeException If an unknown/invalid XML node name was found
364 public final function startElement ($resource, string $element, array $attributes) {
366 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: resource[%s]=%s,element=%s,attributes()=%d - CALLED!', gettype($resource), $resource, $element, count($attributes)));
367 if (!is_resource($resource)) {
369 throw new InvalidArgumentException(sprintf('Parameter resource has unexpected type %s', gettype($resource)), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
370 } elseif (empty($element)) {
372 throw new InvalidArgumentException('Parameter "element" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
375 // Initial method name which will never be called...
376 $methodName = $this->initMethodName;
378 // Make the element name lower-case
379 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: methodName=%s', $methodName));
380 $element = strtolower($element);
382 // Is the element a main node?
383 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: element=%s', $element));
384 if (in_array($element, $this->getMainNodes())) {
385 // Okay, main node found!
386 $methodName = 'start' . StringUtils::convertToClassName($element);
389 $this->setCurrMainNode($element);
390 } elseif (in_array($element, $this->getSubNodes())) {
392 $methodName = 'start' . StringUtils::convertToClassName($element);
394 // Invalid node name found
395 throw new InvalidXmlNodeException([$this, $element, $attributes], XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
399 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Invoking this->%s(attributes()=%d) ...', $methodName, count($attributes)));
400 call_user_func_array([$this, $methodName], $attributes);
403 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!');
407 * Ends the main or sub node by sending out the gathered data
409 * @param $resource An XML resource pointer (currently ignored)
410 * @param $nodeName Name of the node we want to finish
412 * @throws XmlNodeMismatchException If current main node mismatches the closing one
414 public final function finishElement ($resource, string $nodeName) {
416 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: resource[%s]=%s,nodeName=%s - CALLED!', gettype($resource), $resource, $nodeName));
417 if (!is_resource($resource)) {
419 throw new InvalidArgumentException(sprintf('Parameter resource has unexpected type %s', gettype($resource)), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
420 } elseif (empty($nodeName)) {
422 throw new InvalidArgumentException('Parameter "nodeName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
425 // Make all lower-case
426 $nodeName = strtolower($nodeName);
428 // Does this match with current main node?
429 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: nodeName=%s', $nodeName));
430 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
432 throw new XmlNodeMismatchException ([$this, $nodeName, $this->getCurrMainNode()], XmlParser::EXCEPTION_XML_NODE_MISMATCH);
435 // Construct method name
436 $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
438 // Call the corresponding method
439 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Invoking this->%s() ...', $methodName));
440 call_user_func_array([$this, $methodName], []);
443 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!');
447 * Renders the given XML content
449 * @param $content Valid XML content or if not set the current loaded raw content
451 * @throws InvalidArgumentException If a parameter has an invalid value
453 public function renderXmlContent (string $content = NULL) {
454 // Is the content set?
455 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: content[%s]()=%d - CALLED!', gettype($content), strlen($content)));
456 if (is_null($content)) {
457 // Get current content
458 $content = $this->getRawTemplateData();
459 } elseif (empty($content)) {
461 throw new InvalidArgumentException('Parameter "content" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
464 // Get a XmlParser instance
465 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', [$this]);
467 // Check if XML compacting is enabled
468 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: parserInstance=%s', $parserInstance->__toString()));
469 if ($this->isXmlCompactingEnabled()) {
470 // Yes, so get a decorator class for transparent compacting
471 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', [$parserInstance]);
474 // Parse the XML document
475 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Invoking parserInstance->parseXmlContent(content()=%d) ...', strlen($content)));
476 $parserInstance->parseXmlContent($content);
479 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!');
483 * Enables or disables XML compacting
485 * @param $xmlCompacting New XML compacting setting
488 public final function enableXmlCompacting (bool $xmlCompacting = true) {
489 $this->xmlCompacting = $xmlCompacting;
493 * Checks whether XML compacting is enabled
495 * @return $xmlCompacting Whether XML compacting is enabled or disabled
497 public final function isXmlCompactingEnabled () {
498 return $this->xmlCompacting;