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 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 // Set XML template type and prefix
121 $this->xmlTemplateType = $xmlTemplateType;
122 $this->typePrefix = $typePrefix;
123 $this->initMethodName = sprintf('init%s', StringUtils::convertToClassName($this->xmlTemplateType));
125 // Get template instance
126 $applicationInstance = ApplicationHelper::getSelfInstance();
128 // Determine base path
129 $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . FrameworkBootstrap::getRequestInstance()->getRequestElement('app') . '/';
131 // Is the base path valid?
132 if (empty($templateBasePath)) {
133 // Base path is empty
134 throw new BasePathIsEmptyException($this, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
135 } elseif (!is_dir($templateBasePath)) {
137 throw new BasePathIsNoDirectoryException(array($this, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
138 } elseif (!is_readable($templateBasePath)) {
140 throw new BasePathReadProtectedException(array($this, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
144 $this->setTemplateBasePath($templateBasePath);
146 // Set template extensions
147 $this->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
148 $this->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($typePrefix . '_message_template_extension'));
150 // Absolute output path for compiled templates
151 $this->setCompileOutputPath(sprintf('%s%s',
153 FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
156 // Init a variable stacker
157 $stackInstance = ObjectFactory::createObjectByConfiguredName($typePrefix . '_' . $xmlTemplateType . '_stacker_class');
160 $this->stackerName = $typePrefix . '_' . $xmlTemplateType;
163 $stackInstance->initStack($this->stackerName);
166 $this->setStackInstance($stackInstance);
168 // Set it in main nodes
169 array_push($this->mainNodes, str_replace('_', '-', $xmlTemplateType));
173 * Load a specified XML template into the engine
175 * @param $templateName Optional name of template
178 public function loadXmlTemplate (string $templateName = '') {
179 // Is the template name empty?
180 if (empty($templateName)) {
181 // Set generic template name
182 $templateName = $this->typePrefix . '_' . $this->xmlTemplateType . '_template_type';
186 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($templateName));
188 // Load the special template
189 $this->loadTemplate($this->xmlTemplateType);
193 * Getter for current main node
195 * @return $currMainNode Current main node
197 public final function getCurrMainNode () {
198 return $this->curr['main_node'];
202 * Setter for current main node
204 * @param $element Element name to set as current main node
205 * @return $currMainNode Current main node
207 private final function setCurrMainNode (string $element) {
208 $this->curr['main_node'] = $element;
212 * Getter for main node array
214 * @return $mainNodes Array with valid main node names
216 public final function getMainNodes () {
217 return $this->mainNodes;
221 * Getter for stacker name
223 * @return $stackerName Name of stacker of this class
225 protected final function getStackerName () {
226 return $this->stackerName;
230 * Setter for sub node array
232 * @param $subNodes Array with valid sub node names
235 public final function setSubNodes (array $subNodes) {
236 $this->subNodes = $subNodes;
240 * Getter for sub node array
242 * @return $subNodes Array with valid sub node names
244 public final function getSubNodes () {
245 return $this->subNodes;
249 * Read XML variables by calling readVariable() with 'general' as
252 * @param $key Key to read from
253 * @return $value Value from variable
255 public function readXmlData (string $key) {
256 // Is key parameter valid?
257 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: key=%s - CALLED!', $key));
260 throw new InvalidArgumentException('Parameter key is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
264 $value = parent::readVariable($key, 'general');
267 if (is_null($value)) {
268 // Bah, needs fixing.
269 $this->debugInstance(sprintf('[%s:%d]: key=%s returns NULL', __METHOD__, __LINE__, $key));
277 * Handles the template dependency for given XML node
279 * @param $node The XML node we should load a dependency template
280 * @param $templateDependency A template to load to satisfy dependencies
283 protected function handleTemplateDependency (string $node, string $templateDependency) {
284 // Check that the XML node is not empty
285 assert(!empty($node));
287 // Is the template dependency set?
288 if ((!empty($templateDependency)) && (!isset($this->dependencyContent[$node]))) {
289 // Get a temporay template instance
290 $templateInstance = XmlTemplateEngineFactory::createXmlTemplateEngineInstance($this->typePrefix . '_' . self::convertDashesToUnderscores($node) . '_' . $this->xmlTemplateType . '_template_class');
293 $templateInstance->loadXmlTemplate($templateDependency);
295 // Parse the XML content
296 $templateInstance->renderXmlContent();
298 // Save the parsed raw content in our dependency array
299 $this->dependencyContent[$node] = $templateInstance->getRawTemplateData();
304 * Handles the start element of an XML resource
306 * @param $resource XML parser resource (currently ignored)
307 * @param $element The element we shall handle
308 * @param $attributes All attributes
310 * @throws InvalidXmlNodeException If an unknown/invalid XML node name was found
312 public final function startElement ($resource, string $element, array $attributes) {
313 // Initial method name which will never be called...
314 $methodName = $this->initMethodName;
316 // Make the element name lower-case
317 $element = strtolower($element);
319 // Is the element a main node?
320 //* DEBUG: */ echo "START: >".$element."<<br />\n";
321 if (in_array($element, $this->getMainNodes())) {
322 // Okay, main node found!
323 $methodName = 'start' . StringUtils::convertToClassName($element);
326 $this->setCurrMainNode($element);
327 } elseif (in_array($element, $this->getSubNodes())) {
329 $methodName = 'start' . StringUtils::convertToClassName($element);
331 // Invalid node name found
332 throw new InvalidXmlNodeException([$this, $element, $attributes], XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
336 call_user_func_array(array($this, $methodName), $attributes);
340 * Ends the main or sub node by sending out the gathered data
342 * @param $resource An XML resource pointer (currently ignored)
343 * @param $nodeName Name of the node we want to finish
345 * @throws XmlNodeMismatchException If current main node mismatches the closing one
347 public final function finishElement ($resource, string $nodeName) {
348 // Make all lower-case
349 $nodeName = strtolower($nodeName);
351 // Does this match with current main node?
352 //* DEBUG: */ echo "END: >".$nodeName."<<br />\n";
353 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
355 throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), XmlParser::EXCEPTION_XML_NODE_MISMATCH);
358 // Construct method name
359 $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
361 // Call the corresponding method
362 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
363 call_user_func_array(array($this, $methodName), array());
367 * Renders the given XML content
369 * @param $content Valid XML content or if not set the current loaded raw content
371 * @throws XmlParserException If an XML error was found
373 public function renderXmlContent (string $content = NULL) {
374 // Is the content set?
375 if (is_null($content)) {
376 // Get current content
377 $content = $this->getRawTemplateData();
380 // Get a XmlParser instance
381 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', [$this]);
383 // Check if XML compacting is enabled
384 if ($this->isXmlCompactingEnabled()) {
385 // Yes, so get a decorator class for transparent compacting
386 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
389 // Parse the XML document
390 $parserInstance->parseXmlContent($content);
394 * Enables or disables XML compacting
396 * @param $xmlCompacting New XML compacting setting
399 public final function enableXmlCompacting (bool $xmlCompacting = true) {
400 $this->xmlCompacting = $xmlCompacting;
404 * Checks whether XML compacting is enabled
406 * @return $xmlCompacting Whether XML compacting is enabled or disabled
408 public final function isXmlCompactingEnabled () {
409 return $this->xmlCompacting;