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\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\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 * 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_dir($templateBasePath)) {
130 throw new BasePathIsNoDirectoryException(array($this, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
131 } elseif (!is_readable($templateBasePath)) {
133 throw new BasePathReadProtectedException(array($this, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
137 $this->setTemplateBasePath($templateBasePath);
139 // Set template extensions
140 $this->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
141 $this->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($typePrefix . '_message_template_extension'));
143 // Absolute output path for compiled templates
144 $this->setCompileOutputPath(sprintf('%s%s',
146 FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
149 // Init a variable stacker
150 $stackInstance = ObjectFactory::createObjectByConfiguredName($typePrefix . '_' . $xmlTemplateType . '_stacker_class');
153 $this->stackerName = $typePrefix . '_' . $xmlTemplateType;
156 $stackInstance->initStack($this->stackerName);
159 $this->setStackInstance($stackInstance);
161 // Set it in main nodes
162 array_push($this->mainNodes, str_replace('_', '-', $xmlTemplateType));
166 * Load a specified XML template into the engine
168 * @param $templateName Optional name of template
171 public function loadXmlTemplate (string $templateName = '') {
172 // Is the template name empty?
173 if (empty($templateName)) {
174 // Set generic template name
175 $templateName = $this->typePrefix . '_' . $this->xmlTemplateType . '_template_type';
179 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($templateName));
181 // Load the special template
182 $this->loadTemplate($this->xmlTemplateType);
186 * Getter for current main node
188 * @return $currMainNode Current main node
190 public final function getCurrMainNode () {
191 return $this->curr['main_node'];
195 * Setter for current main node
197 * @param $element Element name to set as current main node
198 * @return $currMainNode Current main node
200 private final function setCurrMainNode (string $element) {
201 $this->curr['main_node'] = $element;
205 * Getter for main node array
207 * @return $mainNodes Array with valid main node names
209 public final function getMainNodes () {
210 return $this->mainNodes;
214 * Getter for stacker name
216 * @return $stackerName Name of stacker of this class
218 protected final function getStackerName () {
219 return $this->stackerName;
223 * Setter for sub node array
225 * @param $subNodes Array with valid sub node names
228 public final function setSubNodes (array $subNodes) {
229 $this->subNodes = $subNodes;
233 * Getter for sub node array
235 * @return $subNodes Array with valid sub node names
237 public final function getSubNodes () {
238 return $this->subNodes;
242 * Read XML variables by calling readVariable() with 'general' as
245 * @param $key Key to read from
246 * @return $value Value from variable
248 public function readXmlData (string $key) {
249 // Is key parameter valid?
250 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: key=%s - CALLED!', $key));
253 throw new InvalidArgumentException('Parameter key is empty');
257 $value = parent::readVariable($key, 'general');
260 if (is_null($value)) {
261 // Bah, needs fixing.
262 $this->debugInstance(sprintf('[%s:%d]: key=%s returns NULL', __METHOD__, __LINE__, $key));
270 * Handles the template dependency for given XML node
272 * @param $node The XML node we should load a dependency template
273 * @param $templateDependency A template to load to satisfy dependencies
276 protected function handleTemplateDependency (string $node, string $templateDependency) {
277 // Check that the XML node is not empty
278 assert(!empty($node));
280 // Is the template dependency set?
281 if ((!empty($templateDependency)) && (!isset($this->dependencyContent[$node]))) {
282 // Get a temporay template instance
283 $templateInstance = XmlTemplateEngineFactory::createXmlTemplateEngineInstance($this->typePrefix . '_' . self::convertDashesToUnderscores($node) . '_' . $this->xmlTemplateType . '_template_class');
286 $templateInstance->loadXmlTemplate($templateDependency);
288 // Parse the XML content
289 $templateInstance->renderXmlContent();
291 // Save the parsed raw content in our dependency array
292 $this->dependencyContent[$node] = $templateInstance->getRawTemplateData();
297 * Handles the start element of an XML resource
299 * @param $resource XML parser resource (currently ignored)
300 * @param $element The element we shall handle
301 * @param $attributes All attributes
303 * @throws InvalidXmlNodeException If an unknown/invalid XML node name was found
305 public final function startElement ($resource, string $element, array $attributes) {
306 // Initial method name which will never be called...
307 $methodName = 'init' . StringUtils::convertToClassName($this->xmlTemplateType);
309 // Make the element name lower-case
310 $element = strtolower($element);
312 // Is the element a main node?
313 //* DEBUG: */ echo "START: >".$element."<<br />\n";
314 if (in_array($element, $this->getMainNodes())) {
315 // Okay, main node found!
316 $methodName = 'start' . StringUtils::convertToClassName($element);
319 $this->setCurrMainNode($element);
320 } elseif (in_array($element, $this->getSubNodes())) {
322 $methodName = 'start' . StringUtils::convertToClassName($element);
324 // Invalid node name found
325 throw new InvalidXmlNodeException(array($this, $element, $attributes), XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
329 call_user_func_array(array($this, $methodName), $attributes);
333 * Ends the main or sub node by sending out the gathered data
335 * @param $resource An XML resource pointer (currently ignored)
336 * @param $nodeName Name of the node we want to finish
338 * @throws XmlNodeMismatchException If current main node mismatches the closing one
340 public final function finishElement ($resource, string $nodeName) {
341 // Make all lower-case
342 $nodeName = strtolower($nodeName);
344 // Does this match with current main node?
345 //* DEBUG: */ echo "END: >".$nodeName."<<br />\n";
346 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
348 throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), XmlParser::EXCEPTION_XML_NODE_MISMATCH);
351 // Construct method name
352 $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
354 // Call the corresponding method
355 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
356 call_user_func_array(array($this, $methodName), array());
360 * Renders the given XML content
362 * @param $content Valid XML content or if not set the current loaded raw content
364 * @throws XmlParserException If an XML error was found
366 public function renderXmlContent (string $content = NULL) {
367 // Is the content set?
368 if (is_null($content)) {
369 // Get current content
370 $content = $this->getRawTemplateData();
373 // Get a XmlParser instance
374 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', [$this]);
376 // Check if XML compacting is enabled
377 if ($this->isXmlCompactingEnabled()) {
378 // Yes, so get a decorator class for transparent compacting
379 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
382 // Parse the XML document
383 $parserInstance->parseXmlContent($content);
387 * Enables or disables XML compacting
389 * @param $xmlCompacting New XML compacting setting
392 public final function enableXmlCompacting (bool $xmlCompacting = true) {
393 $this->xmlCompacting = $xmlCompacting;
397 * Checks whether XML compacting is enabled
399 * @return $xmlCompacting Whether XML compacting is enabled or disabled
401 public final function isXmlCompactingEnabled () {
402 return $this->xmlCompacting;