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\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;
20 use \InvalidArgumentException;
23 * A generic XML template engine class
25 * @author Roland Haeder <webmaster@shipsimu.org>
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()
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.
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.
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/>.
45 abstract class BaseXmlTemplateEngine extends BaseTemplateEngine implements CompileableXmlTemplate {
47 use CompileableTemplateTrait;
51 * Main nodes in the XML tree
53 private $mainNodes = [];
56 * Sub nodes in the XML tree
58 private $subNodes = [];
68 private $xmlTemplateType = 'xml';
73 private $typePrefix = 'xml';
78 private $stackerName = '';
81 * Content from dependency
83 protected $dependencyContent = [];
86 * XML compacting is disabled by default
88 private $xmlCompacting = false;
91 * Method name for XML template type
93 private $initMethodName = 'invalid';
96 * Protected constructor
98 * @param $className Name of the class
101 protected function __construct (string $className) {
102 // Call parent constructor
103 parent::__construct($className);
107 * Does a generic initialization of the template engine
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
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)) {
125 throw new InvalidArgumentException('Parameter "typePrefix" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
126 } elseif (empty($xmlTemplateType)) {
128 throw new InvalidArgumentException('Parameter "xmlTemplateType" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
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));
136 // Get template instance
137 $applicationInstance = ApplicationHelper::getSelfInstance();
139 // Determine base path
140 $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . FrameworkBootstrap::getRequestInstance()->getRequestElement('app') . '/';
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)) {
148 throw new BasePathIsNoDirectoryException(array($this, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
149 } elseif (!is_readable($templateBasePath)) {
151 throw new BasePathReadProtectedException(array($this, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
155 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: templateBasePath=%s', $templateBasePath));
156 $this->setTemplateBasePath($templateBasePath);
158 // Set template extensions
159 $this->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
160 $this->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($typePrefix . '_message_template_extension'));
162 // Absolute output path for compiled templates
163 $this->setCompileOutputPath(sprintf('%s%s',
165 FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
168 // Init a variable stacker
169 $stackInstance = ObjectFactory::createObjectByConfiguredName($typePrefix . '_' . $xmlTemplateType . '_stacker_class');
172 $this->stackerName = $typePrefix . '_' . $xmlTemplateType;
175 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: this->stackerName=%s', $this->stackerName));
176 $stackInstance->initStack($this->stackerName);
179 $this->setStackInstance($stackInstance);
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));
186 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-XML-TEMPLATE-ENGINE: CALLED!');
190 * Load a specified XML template into the engine
192 * @param $templateName Optional name of template
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';
204 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($templateName));
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);
211 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-XML-TEMPLATE-ENGINE: CALLED!');
215 * Getter for current main node
217 * @return $currMainNode Current main node
219 public final function getCurrMainNode () {
220 return $this->curr['main_node'];
224 * Setter for current main node
226 * @param $element Element name to set as current main node
227 * @return $currMainNode Current main node
229 private final function setCurrMainNode (string $element) {
230 $this->curr['main_node'] = $element;
234 * Getter for main node array
236 * @return $mainNodes Array with valid main node names
238 public final function getMainNodes () {
239 return $this->mainNodes;
243 * Getter for stacker name
245 * @return $stackerName Name of stacker of this class
247 protected final function getStackerName () {
248 return $this->stackerName;
252 * Setter for sub node array
254 * @param $subNodes Array with valid sub node names
257 public final function setSubNodes (array $subNodes) {
258 $this->subNodes = $subNodes;
262 * Getter for sub node array
264 * @return $subNodes Array with valid sub node names
266 public final function getSubNodes () {
267 return $this->subNodes;
271 * Read XML variables by calling readVariable() with 'general' as
274 * @param $key Key to read from
275 * @return $value Value from variable
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));
282 throw new InvalidArgumentException('Parameter key is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
286 $value = parent::readVariable($key, 'general');
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));
296 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: value=%s - EXIT!', $value));
301 * Handles the template dependency for given XML node
303 * @param $node The XML node we should load a dependency template
304 * @param $templateDependency A template to load to satisfy dependencies
306 * @throws InvalidArgumentException If a parameter has an invalid value
308 protected function handleTemplateDependency (string $node, string $templateDependency) {
310 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: node=%s,templateDependency=%s - CALLED!', $node, $templateDependency));
313 throw new InvalidArgumentException('Parameter "node" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
314 } elseif (empty($templateDependency)) {
316 throw new InvalidArgumentException('Parameter "templateDependency" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
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');
325 $templateInstance->loadXmlTemplate($templateDependency);
327 // Parse the XML content
328 $templateInstance->renderXmlContent();
330 // Save the parsed raw content in our dependency array
331 $this->dependencyContent[$node] = $templateInstance->getRawTemplateData();
335 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-XML-TEMPLATE-ENGINE: CALLED!');
339 * Handles the start element of an XML resource
341 * @param $resource XML parser resource (currently ignored)
342 * @param $element The element we shall handle
343 * @param $attributes All attributes
345 * @throws InvalidArgumentException If a parameter has an invalid value
346 * @throws InvalidXmlNodeException If an unknown/invalid XML node name was found
348 public final function startElement ($resource, string $element, array $attributes) {
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)) {
353 throw new InvalidArgumentException(sprintf('Parameter resource has unexpected type %s', gettype($resource)), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
354 } elseif (empty($element)) {
356 throw new InvalidArgumentException('Parameter "element" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
359 // Initial method name which will never be called...
360 $methodName = $this->initMethodName;
362 // Make the element name lower-case
363 $element = strtolower($element);
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);
371 $this->setCurrMainNode($element);
372 } elseif (in_array($element, $this->getSubNodes())) {
374 $methodName = 'start' . StringUtils::convertToClassName($element);
376 // Invalid node name found
377 throw new InvalidXmlNodeException([$this, $element, $attributes], XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
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);
385 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-XML-TEMPLATE-ENGINE: CALLED!');
389 * Ends the main or sub node by sending out the gathered data
391 * @param $resource An XML resource pointer (currently ignored)
392 * @param $nodeName Name of the node we want to finish
394 * @throws XmlNodeMismatchException If current main node mismatches the closing one
396 public final function finishElement ($resource, string $nodeName) {
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)) {
401 throw new InvalidArgumentException(sprintf('Parameter resource has unexpected type %s', gettype($resource)), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
402 } elseif (empty($nodeName)) {
404 throw new InvalidArgumentException('Parameter "nodeName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
407 // Make all lower-case
408 $nodeName = strtolower($nodeName);
410 // Does this match with current main node?
411 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
413 throw new XmlNodeMismatchException ([$this, $nodeName, $this->getCurrMainNode()], XmlParser::EXCEPTION_XML_NODE_MISMATCH);
416 // Construct method name
417 $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
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], []);
424 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-XML-TEMPLATE-ENGINE: CALLED!');
428 * Renders the given XML content
430 * @param $content Valid XML content or if not set the current loaded raw content
432 * @throws XmlParserException If an XML error was found
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();
442 // Get a XmlParser instance
443 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', [$this]);
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]);
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);
456 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-XML-TEMPLATE-ENGINE: CALLED!');
460 * Enables or disables XML compacting
462 * @param $xmlCompacting New XML compacting setting
465 public final function enableXmlCompacting (bool $xmlCompacting = true) {
466 $this->xmlCompacting = $xmlCompacting;
470 * Checks whether XML compacting is enabled
472 * @return $xmlCompacting Whether XML compacting is enabled or disabled
474 public final function isXmlCompactingEnabled () {
475 return $this->xmlCompacting;