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\Helper\Application\ApplicationHelper;
10 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
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\String\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 * Protected constructor
92 * @param $className Name of the class
95 protected function __construct (string $className) {
96 // Call parent constructor
97 parent::__construct($className);
101 * Does a generic initialization of the template engine
103 * @param $typePrefix Type prefix
104 * @param $xmlTemplateType Type of XML template
105 * @return $templateInstance An instance of TemplateEngine
106 * @throws BasePathIsEmptyException If the provided $templateBasePath is empty
107 * @throws InvalidBasePathStringException If $templateBasePath is no string
108 * @throws BasePathIsNoDirectoryException If $templateBasePath is no
109 * directory or not found
110 * @throws BasePathReadProtectedException If $templateBasePath is
113 protected function initXmlTemplateEngine (string $typePrefix, string $xmlTemplateType) {
114 // Set XML template type and prefix
115 $this->xmlTemplateType = $xmlTemplateType;
116 $this->typePrefix = $typePrefix;
118 // Get template instance
119 $applicationInstance = ApplicationHelper::getSelfInstance();
121 // Determine base path
122 $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . FrameworkBootstrap::getRequestInstance()->getRequestElement('app') . '/';
124 // Is the base path valid?
125 if (empty($templateBasePath)) {
126 // Base path is empty
127 throw new BasePathIsEmptyException($this, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
128 } elseif (!is_string($templateBasePath)) {
130 throw new InvalidBasePathStringException(array($this, $templateBasePath), self::EXCEPTION_INVALID_STRING);
131 } elseif (!is_dir($templateBasePath)) {
133 throw new BasePathIsNoDirectoryException(array($this, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
134 } elseif (!is_readable($templateBasePath)) {
136 throw new BasePathReadProtectedException(array($this, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
140 $this->setTemplateBasePath($templateBasePath);
142 // Set template extensions
143 $this->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
144 $this->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($typePrefix . '_message_template_extension'));
146 // Absolute output path for compiled templates
147 $this->setCompileOutputPath(sprintf('%s%s',
149 FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
152 // Init a variable stacker
153 $stackInstance = ObjectFactory::createObjectByConfiguredName($typePrefix . '_' . $xmlTemplateType . '_stacker_class');
156 $this->stackerName = $typePrefix . '_' . $xmlTemplateType;
159 $stackInstance->initStack($this->stackerName);
162 $this->setStackInstance($stackInstance);
164 // Set it in main nodes
165 array_push($this->mainNodes, str_replace('_', '-', $xmlTemplateType));
169 * Load a specified XML template into the engine
171 * @param $templateName Optional name of template
174 public function loadXmlTemplate (string $templateName = '') {
175 // Is the template name empty?
176 if (empty($templateName)) {
177 // Set generic template name
178 $templateName = $this->typePrefix . '_' . $this->xmlTemplateType . '_template_type';
182 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($templateName));
184 // Load the special template
185 $this->loadTemplate($this->xmlTemplateType);
189 * Getter for current main node
191 * @return $currMainNode Current main node
193 public final function getCurrMainNode () {
194 return $this->curr['main_node'];
198 * Setter for current main node
200 * @param $element Element name to set as current main node
201 * @return $currMainNode Current main node
203 private final function setCurrMainNode (string $element) {
204 $this->curr['main_node'] = $element;
208 * Getter for main node array
210 * @return $mainNodes Array with valid main node names
212 public final function getMainNodes () {
213 return $this->mainNodes;
217 * Getter for stacker name
219 * @return $stackerName Name of stacker of this class
221 protected final function getStackerName () {
222 return $this->stackerName;
226 * Setter for sub node array
228 * @param $subNodes Array with valid sub node names
231 public final function setSubNodes (array $subNodes) {
232 $this->subNodes = $subNodes;
236 * Getter for sub node array
238 * @return $subNodes Array with valid sub node names
240 public final function getSubNodes () {
241 return $this->subNodes;
245 * Read XML variables by calling readVariable() with 'general' as
248 * @param $key Key to read from
249 * @return $value Value from variable
251 public function readXmlData (string $key) {
252 // Is key parameter valid?
253 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: key=%s - CALLED!', $key));
256 throw new InvalidArgumentException('Parameter key is empty');
260 $value = parent::readVariable($key, 'general');
263 if (is_null($value)) {
264 // Bah, needs fixing.
265 $this->debugInstance(sprintf('[%s:%d]: key=%s returns NULL', __METHOD__, __LINE__, $key));
273 * Handles the template dependency for given XML node
275 * @param $node The XML node we should load a dependency template
276 * @param $templateDependency A template to load to satisfy dependencies
279 protected function handleTemplateDependency (string $node, string $templateDependency) {
280 // Check that the XML node is not empty
281 assert(!empty($node));
283 // Is the template dependency set?
284 if ((!empty($templateDependency)) && (!isset($this->dependencyContent[$node]))) {
285 // Get a temporay template instance
286 $templateInstance = XmlTemplateEngineFactory::createXmlTemplateEngineInstance($this->typePrefix . '_' . self::convertDashesToUnderscores($node) . '_' . $this->xmlTemplateType . '_template_class');
289 $templateInstance->loadXmlTemplate($templateDependency);
291 // Parse the XML content
292 $templateInstance->renderXmlContent();
294 // Save the parsed raw content in our dependency array
295 $this->dependencyContent[$node] = $templateInstance->getRawTemplateData();
300 * Handles the start element of an XML resource
302 * @param $resource XML parser resource (currently ignored)
303 * @param $element The element we shall handle
304 * @param $attributes All attributes
306 * @throws InvalidXmlNodeException If an unknown/invalid XML node name was found
308 public final function startElement ($resource, string $element, array $attributes) {
309 // Initial method name which will never be called...
310 $methodName = 'init' . StringUtils::convertToClassName($this->xmlTemplateType);
312 // Make the element name lower-case
313 $element = strtolower($element);
315 // Is the element a main node?
316 //* DEBUG: */ echo "START: >".$element."<<br />\n";
317 if (in_array($element, $this->getMainNodes())) {
318 // Okay, main node found!
319 $methodName = 'start' . StringUtils::convertToClassName($element);
322 $this->setCurrMainNode($element);
323 } elseif (in_array($element, $this->getSubNodes())) {
325 $methodName = 'start' . StringUtils::convertToClassName($element);
327 // Invalid node name found
328 throw new InvalidXmlNodeException(array($this, $element, $attributes), XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
332 call_user_func_array(array($this, $methodName), $attributes);
336 * Ends the main or sub node by sending out the gathered data
338 * @param $resource An XML resource pointer (currently ignored)
339 * @param $nodeName Name of the node we want to finish
341 * @throws XmlNodeMismatchException If current main node mismatches the closing one
343 public final function finishElement ($resource, string $nodeName) {
344 // Make all lower-case
345 $nodeName = strtolower($nodeName);
347 // Does this match with current main node?
348 //* DEBUG: */ echo "END: >".$nodeName."<<br />\n";
349 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
351 throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), XmlParser::EXCEPTION_XML_NODE_MISMATCH);
354 // Construct method name
355 $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
357 // Call the corresponding method
358 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
359 call_user_func_array(array($this, $methodName), array());
363 * Renders the given XML content
365 * @param $content Valid XML content or if not set the current loaded raw content
367 * @throws XmlParserException If an XML error was found
369 public function renderXmlContent (string $content = NULL) {
370 // Is the content set?
371 if (is_null($content)) {
372 // Get current content
373 $content = $this->getRawTemplateData();
376 // Get a XmlParser instance
377 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
379 // Check if XML compacting is enabled
380 if ($this->isXmlCompactingEnabled()) {
381 // Yes, so get a decorator class for transparent compacting
382 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
385 // Parse the XML document
386 $parserInstance->parseXmlContent($content);
390 * Enables or disables XML compacting
392 * @param $xmlCompacting New XML compacting setting
395 public final function enableXmlCompacting (bool $xmlCompacting = true) {
396 $this->xmlCompacting = $xmlCompacting;
400 * Checks whether XML compacting is enabled
402 * @return $xmlCompacting Whether XML compacting is enabled or disabled
404 public final function isXmlCompactingEnabled () {
405 return $this->xmlCompacting;