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\ObjectFactory;
8 use Org\Mxchange\CoreFramework\Factory\Template\XmlTemplateEngineFactory;
9 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
10 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
11 use Org\Mxchange\CoreFramework\Template\Engine\BaseTemplateEngine;
12 use Org\Mxchange\CoreFramework\Template\Xml\CompileableXmlTemplate;
13 use Org\Mxchange\CoreFramework\Traits\Stack\StackableTrait;
14 use Org\Mxchange\CoreFramework\Traits\Template\CompileableTemplateTrait;
15 use Org\Mxchange\CoreFramework\Utils\String\StringUtils;
18 use \InvalidArgumentException;
21 * A generic XML template engine class
23 * @author Roland Haeder <webmaster@shipsimu.org>
25 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2018 Hub Developer Team
26 * @license GNU GPL 3.0 or any newer version
27 * @link http://www.shipsimu.org
28 * @todo This template engine does not make use of setTemplateType()
30 * This program is free software: you can redistribute it and/or modify
31 * it under the terms of the GNU General Public License as published by
32 * the Free Software Foundation, either version 3 of the License, or
33 * (at your option) any later version.
35 * This program is distributed in the hope that it will be useful,
36 * but WITHOUT ANY WARRANTY; without even the implied warranty of
37 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
38 * GNU General Public License for more details.
40 * You should have received a copy of the GNU General Public License
41 * along with this program. If not, see <http://www.gnu.org/licenses/>.
43 abstract class BaseXmlTemplateEngine extends BaseTemplateEngine implements CompileableXmlTemplate {
45 use CompileableTemplateTrait;
49 * Main nodes in the XML tree
51 private $mainNodes = [];
54 * Sub nodes in the XML tree
56 private $subNodes = [];
66 private $xmlTemplateType = 'xml';
71 private $typePrefix = 'xml';
76 private $stackerName = '';
79 * Content from dependency
81 protected $dependencyContent = [];
84 * XML compacting is disabled by default
86 private $xmlCompacting = false;
89 * Protected constructor
91 * @param $className Name of the class
94 protected function __construct (string $className) {
95 // Call parent constructor
96 parent::__construct($className);
100 * Does a generic initialization of the template engine
102 * @param $typePrefix Type prefix
103 * @param $xmlTemplateType Type of XML template
104 * @return $templateInstance An instance of TemplateEngine
105 * @throws BasePathIsEmptyException If the provided $templateBasePath is empty
106 * @throws InvalidBasePathStringException If $templateBasePath is no string
107 * @throws BasePathIsNoDirectoryException If $templateBasePath is no
108 * directory or not found
109 * @throws BasePathReadProtectedException If $templateBasePath is
112 protected function initXmlTemplateEngine (string $typePrefix, string $xmlTemplateType) {
113 // Set XML template type and prefix
114 $this->xmlTemplateType = $xmlTemplateType;
115 $this->typePrefix = $typePrefix;
117 // Get template instance
118 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
120 // Determine base path
121 $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . FrameworkBootstrap::getRequestInstance()->getRequestElement('app') . '/';
123 // Is the base path valid?
124 if (empty($templateBasePath)) {
125 // Base path is empty
126 throw new BasePathIsEmptyException($this, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
127 } elseif (!is_string($templateBasePath)) {
129 throw new InvalidBasePathStringException(array($this, $templateBasePath), self::EXCEPTION_INVALID_STRING);
130 } elseif (!is_dir($templateBasePath)) {
132 throw new BasePathIsNoDirectoryException(array($this, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
133 } elseif (!is_readable($templateBasePath)) {
135 throw new BasePathReadProtectedException(array($this, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
139 $this->setTemplateBasePath($templateBasePath);
141 // Set template extensions
142 $this->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
143 $this->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($typePrefix . '_message_template_extension'));
145 // Absolute output path for compiled templates
146 $this->setCompileOutputPath(sprintf('%s%s',
148 FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
151 // Init a variable stacker
152 $stackInstance = ObjectFactory::createObjectByConfiguredName($typePrefix . '_' . $xmlTemplateType . '_stacker_class');
155 $this->stackerName = $typePrefix . '_' . $xmlTemplateType;
158 $stackInstance->initStack($this->stackerName);
161 $this->setStackInstance($stackInstance);
163 // Set it in main nodes
164 array_push($this->mainNodes, str_replace('_', '-', $xmlTemplateType));
168 * Load a specified XML template into the engine
170 * @param $templateName Optional name of template
173 public function loadXmlTemplate (string $templateName = '') {
174 // Is the template name empty?
175 if (empty($templateName)) {
176 // Set generic template name
177 $templateName = $this->typePrefix . '_' . $this->xmlTemplateType . '_template_type';
181 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($templateName));
183 // Load the special template
184 $this->loadTemplate($this->xmlTemplateType);
188 * Getter for current main node
190 * @return $currMainNode Current main node
192 public final function getCurrMainNode () {
193 return $this->curr['main_node'];
197 * Setter for current main node
199 * @param $element Element name to set as current main node
200 * @return $currMainNode Current main node
202 private final function setCurrMainNode (string $element) {
203 $this->curr['main_node'] = $element;
207 * Getter for main node array
209 * @return $mainNodes Array with valid main node names
211 public final function getMainNodes () {
212 return $this->mainNodes;
216 * Getter for stacker name
218 * @return $stackerName Name of stacker of this class
220 protected final function getStackerName () {
221 return $this->stackerName;
225 * Setter for sub node array
227 * @param $subNodes Array with valid sub node names
230 public final function setSubNodes (array $subNodes) {
231 $this->subNodes = $subNodes;
235 * Getter for sub node array
237 * @return $subNodes Array with valid sub node names
239 public final function getSubNodes () {
240 return $this->subNodes;
244 * Read XML variables by calling readVariable() with 'general' as
247 * @param $key Key to read from
248 * @return $value Value from variable
250 public function readXmlData (string $key) {
251 // Is key parameter valid?
252 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: key=%s - CALLED!', $key));
255 throw new InvalidArgumentException('Parameter key is empty');
259 $value = parent::readVariable($key, 'general');
262 if (is_null($value)) {
263 // Bah, needs fixing.
264 $this->debugInstance(sprintf('[%s:%d]: key=%s returns NULL', __METHOD__, __LINE__, $key));
272 * Handles the template dependency for given XML node
274 * @param $node The XML node we should load a dependency template
275 * @param $templateDependency A template to load to satisfy dependencies
278 protected function handleTemplateDependency (string $node, string $templateDependency) {
279 // Check that the XML node is not empty
280 assert(!empty($node));
282 // Is the template dependency set?
283 if ((!empty($templateDependency)) && (!isset($this->dependencyContent[$node]))) {
284 // Get a temporay template instance
285 $templateInstance = XmlTemplateEngineFactory::createXmlTemplateEngineInstance($this->typePrefix . '_' . self::convertDashesToUnderscores($node) . '_' . $this->xmlTemplateType . '_template_class');
288 $templateInstance->loadXmlTemplate($templateDependency);
290 // Parse the XML content
291 $templateInstance->renderXmlContent();
293 // Save the parsed raw content in our dependency array
294 $this->dependencyContent[$node] = $templateInstance->getRawTemplateData();
299 * Handles the start element of an XML resource
301 * @param $resource XML parser resource (currently ignored)
302 * @param $element The element we shall handle
303 * @param $attributes All attributes
305 * @throws InvalidXmlNodeException If an unknown/invalid XML node name was found
307 public final function startElement ($resource, string $element, array $attributes) {
308 // Initial method name which will never be called...
309 $methodName = 'init' . StringUtils::convertToClassName($this->xmlTemplateType);
311 // Make the element name lower-case
312 $element = strtolower($element);
314 // Is the element a main node?
315 //* DEBUG: */ echo "START: >".$element."<<br />\n";
316 if (in_array($element, $this->getMainNodes())) {
317 // Okay, main node found!
318 $methodName = 'start' . StringUtils::convertToClassName($element);
321 $this->setCurrMainNode($element);
322 } elseif (in_array($element, $this->getSubNodes())) {
324 $methodName = 'start' . StringUtils::convertToClassName($element);
326 // Invalid node name found
327 throw new InvalidXmlNodeException(array($this, $element, $attributes), XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
331 call_user_func_array(array($this, $methodName), $attributes);
335 * Ends the main or sub node by sending out the gathered data
337 * @param $resource An XML resource pointer (currently ignored)
338 * @param $nodeName Name of the node we want to finish
340 * @throws XmlNodeMismatchException If current main node mismatches the closing one
342 public final function finishElement ($resource, string $nodeName) {
343 // Make all lower-case
344 $nodeName = strtolower($nodeName);
346 // Does this match with current main node?
347 //* DEBUG: */ echo "END: >".$nodeName."<<br />\n";
348 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
350 throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), XmlParser::EXCEPTION_XML_NODE_MISMATCH);
353 // Construct method name
354 $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
356 // Call the corresponding method
357 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
358 call_user_func_array(array($this, $methodName), array());
362 * Renders the given XML content
364 * @param $content Valid XML content or if not set the current loaded raw content
366 * @throws XmlParserException If an XML error was found
368 public function renderXmlContent (string $content = NULL) {
369 // Is the content set?
370 if (is_null($content)) {
371 // Get current content
372 $content = $this->getRawTemplateData();
375 // Get a XmlParser instance
376 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
378 // Check if XML compacting is enabled
379 if ($this->isXmlCompactingEnabled()) {
380 // Yes, so get a decorator class for transparent compacting
381 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
384 // Parse the XML document
385 $parserInstance->parseXmlContent($content);
389 * Enables or disables XML compacting
391 * @param $xmlCompacting New XML compacting setting
394 public final function enableXmlCompacting (bool $xmlCompacting = true) {
395 $this->xmlCompacting = $xmlCompacting;
399 * Checks whether XML compacting is enabled
401 * @return $xmlCompacting Whether XML compacting is enabled or disabled
403 public final function isXmlCompactingEnabled () {
404 return $this->xmlCompacting;