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 parent::__construct($className);
106 * Does a generic initialization of the template engine
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
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)) {
124 throw new InvalidArgumentException('Parameter "typePrefix" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
125 } elseif (empty($xmlTemplateType)) {
127 throw new InvalidArgumentException('Parameter "xmlTemplateType" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
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));
135 // Get template instance
136 $applicationInstance = ApplicationHelper::getSelfInstance();
138 // Determine base path
139 $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . FrameworkBootstrap::getRequestInstance()->getRequestElement('app') . '/';
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)) {
147 throw new BasePathIsNoDirectoryException(array($this, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
148 } elseif (!is_readable($templateBasePath)) {
150 throw new BasePathReadProtectedException(array($this, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
154 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: templateBasePath=%s', $templateBasePath));
155 $this->setTemplateBasePath($templateBasePath);
157 // Set template extensions
158 $this->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
159 $this->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($typePrefix . '_message_template_extension'));
161 // Absolute output path for compiled templates
162 $this->setCompileOutputPath(sprintf('%s%s',
164 FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
167 // Init a variable stacker
168 $stackInstance = ObjectFactory::createObjectByConfiguredName($typePrefix . '_' . $xmlTemplateType . '_stacker_class');
171 $this->stackerName = $typePrefix . '_' . $xmlTemplateType;
174 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: this->stackerName=%s', $this->stackerName));
175 $stackInstance->initStack($this->stackerName);
178 $this->setStackInstance($stackInstance);
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));
185 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-XML-TEMPLATE-ENGINE: CALLED!');
189 * Load a specified XML template into the engine
191 * @param $templateName Optional name of template
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';
203 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($templateName));
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);
210 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-XML-TEMPLATE-ENGINE: CALLED!');
214 * Getter for current main node
216 * @return $currMainNode Current main node
218 public final function getCurrMainNode () {
219 return $this->curr['main_node'];
223 * Setter for current main node
225 * @param $element Element name to set as current main node
226 * @return $currMainNode Current main node
228 private final function setCurrMainNode (string $element) {
229 $this->curr['main_node'] = $element;
233 * Getter for main node array
235 * @return $mainNodes Array with valid main node names
237 public final function getMainNodes () {
238 return $this->mainNodes;
242 * Getter for stacker name
244 * @return $stackerName Name of stacker of this class
246 protected final function getStackerName () {
247 return $this->stackerName;
251 * Setter for sub node array
253 * @param $subNodes Array with valid sub node names
256 public final function setSubNodes (array $subNodes) {
257 $this->subNodes = $subNodes;
261 * Getter for sub node array
263 * @return $subNodes Array with valid sub node names
265 public final function getSubNodes () {
266 return $this->subNodes;
270 * Read XML variables by calling readVariable() with 'general' as
273 * @param $key Key to read from
274 * @return $value Value from variable
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));
281 throw new InvalidArgumentException('Parameter key is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
285 $value = parent::readVariable($key, 'general');
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));
295 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: value=%s - EXIT!', $value));
300 * Handles the template dependency for given XML node
302 * @param $node The XML node we should load a dependency template
303 * @param $templateDependency A template to load to satisfy dependencies
305 * @throws InvalidArgumentException If a parameter has an invalid value
307 protected function handleTemplateDependency (string $node, string $templateDependency) {
309 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: node=%s,templateDependency=%s - CALLED!', $node, $templateDependency));
312 throw new InvalidArgumentException('Parameter "node" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
313 } elseif (empty($templateDependency)) {
315 throw new InvalidArgumentException('Parameter "templateDependency" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
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');
324 $templateInstance->loadXmlTemplate($templateDependency);
326 // Parse the XML content
327 $templateInstance->renderXmlContent();
329 // Save the parsed raw content in our dependency array
330 $this->dependencyContent[$node] = $templateInstance->getRawTemplateData();
334 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-XML-TEMPLATE-ENGINE: CALLED!');
338 * Handles the start element of an XML resource
340 * @param $resource XML parser resource (currently ignored)
341 * @param $element The element we shall handle
342 * @param $attributes All attributes
344 * @throws InvalidArgumentException If a parameter has an invalid value
345 * @throws InvalidXmlNodeException If an unknown/invalid XML node name was found
347 public final function startElement ($resource, string $element, array $attributes) {
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)) {
352 throw new InvalidArgumentException(sprintf('Parameter resource has unexpected type %s', gettype($resource)), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
353 } elseif (empty($element)) {
355 throw new InvalidArgumentException('Parameter "element" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
358 // Initial method name which will never be called...
359 $methodName = $this->initMethodName;
361 // Make the element name lower-case
362 $element = strtolower($element);
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);
370 $this->setCurrMainNode($element);
371 } elseif (in_array($element, $this->getSubNodes())) {
373 $methodName = 'start' . StringUtils::convertToClassName($element);
375 // Invalid node name found
376 throw new InvalidXmlNodeException([$this, $element, $attributes], XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
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);
384 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-XML-TEMPLATE-ENGINE: CALLED!');
388 * Ends the main or sub node by sending out the gathered data
390 * @param $resource An XML resource pointer (currently ignored)
391 * @param $nodeName Name of the node we want to finish
393 * @throws XmlNodeMismatchException If current main node mismatches the closing one
395 public final function finishElement ($resource, string $nodeName) {
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)) {
400 throw new InvalidArgumentException(sprintf('Parameter resource has unexpected type %s', gettype($resource)), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
401 } elseif (empty($nodeName)) {
403 throw new InvalidArgumentException('Parameter "nodeName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
406 // Make all lower-case
407 $nodeName = strtolower($nodeName);
409 // Does this match with current main node?
410 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
412 throw new XmlNodeMismatchException ([$this, $nodeName, $this->getCurrMainNode()], XmlParser::EXCEPTION_XML_NODE_MISMATCH);
415 // Construct method name
416 $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
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], []);
423 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-XML-TEMPLATE-ENGINE: CALLED!');
427 * Renders the given XML content
429 * @param $content Valid XML content or if not set the current loaded raw content
431 * @throws XmlParserException If an XML error was found
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();
441 // Get a XmlParser instance
442 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', [$this]);
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]);
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);
455 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-XML-TEMPLATE-ENGINE: CALLED!');
459 * Enables or disables XML compacting
461 * @param $xmlCompacting New XML compacting setting
464 public final function enableXmlCompacting (bool $xmlCompacting = true) {
465 $this->xmlCompacting = $xmlCompacting;
469 * Checks whether XML compacting is enabled
471 * @return $xmlCompacting Whether XML compacting is enabled or disabled
473 public final function isXmlCompactingEnabled () {
474 return $this->xmlCompacting;