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 * Method name for XML template type
92 private $initMethodName = 'invalid';
95 * Protected constructor
97 * @param $className Name of the class
100 protected function __construct (string $className) {
101 // Call parent constructor
102 parent::__construct($className);
106 * Does a generic initialization of the template engine
108 * @param $typePrefix Type prefix
109 * @param $xmlTemplateType Type of XML template
110 * @return $templateInstance An instance of TemplateEngine
111 * @throws BasePathIsEmptyException If the provided $templateBasePath is empty
112 * @throws InvalidBasePathStringException If $templateBasePath is no string
113 * @throws BasePathIsNoDirectoryException If $templateBasePath is no
114 * directory or not found
115 * @throws BasePathReadProtectedException If $templateBasePath is
118 protected function initXmlTemplateEngine (string $typePrefix, string $xmlTemplateType) {
119 // Set XML template type and prefix
120 $this->xmlTemplateType = $xmlTemplateType;
121 $this->typePrefix = $typePrefix;
122 $this->initMethodName = sprintf('init%s', StringUtils::convertToClassName($this->xmlTemplateType));
124 // Get template instance
125 $applicationInstance = ApplicationHelper::getSelfInstance();
127 // Determine base path
128 $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . FrameworkBootstrap::getRequestInstance()->getRequestElement('app') . '/';
130 // Is the base path valid?
131 if (empty($templateBasePath)) {
132 // Base path is empty
133 throw new BasePathIsEmptyException($this, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
134 } elseif (!is_dir($templateBasePath)) {
136 throw new BasePathIsNoDirectoryException(array($this, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
137 } elseif (!is_readable($templateBasePath)) {
139 throw new BasePathReadProtectedException(array($this, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
143 $this->setTemplateBasePath($templateBasePath);
145 // Set template extensions
146 $this->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
147 $this->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($typePrefix . '_message_template_extension'));
149 // Absolute output path for compiled templates
150 $this->setCompileOutputPath(sprintf('%s%s',
152 FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
155 // Init a variable stacker
156 $stackInstance = ObjectFactory::createObjectByConfiguredName($typePrefix . '_' . $xmlTemplateType . '_stacker_class');
159 $this->stackerName = $typePrefix . '_' . $xmlTemplateType;
162 $stackInstance->initStack($this->stackerName);
165 $this->setStackInstance($stackInstance);
167 // Set it in main nodes
168 array_push($this->mainNodes, str_replace('_', '-', $xmlTemplateType));
172 * Load a specified XML template into the engine
174 * @param $templateName Optional name of template
177 public function loadXmlTemplate (string $templateName = '') {
178 // Is the template name empty?
179 if (empty($templateName)) {
180 // Set generic template name
181 $templateName = $this->typePrefix . '_' . $this->xmlTemplateType . '_template_type';
185 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($templateName));
187 // Load the special template
188 $this->loadTemplate($this->xmlTemplateType);
192 * Getter for current main node
194 * @return $currMainNode Current main node
196 public final function getCurrMainNode () {
197 return $this->curr['main_node'];
201 * Setter for current main node
203 * @param $element Element name to set as current main node
204 * @return $currMainNode Current main node
206 private final function setCurrMainNode (string $element) {
207 $this->curr['main_node'] = $element;
211 * Getter for main node array
213 * @return $mainNodes Array with valid main node names
215 public final function getMainNodes () {
216 return $this->mainNodes;
220 * Getter for stacker name
222 * @return $stackerName Name of stacker of this class
224 protected final function getStackerName () {
225 return $this->stackerName;
229 * Setter for sub node array
231 * @param $subNodes Array with valid sub node names
234 public final function setSubNodes (array $subNodes) {
235 $this->subNodes = $subNodes;
239 * Getter for sub node array
241 * @return $subNodes Array with valid sub node names
243 public final function getSubNodes () {
244 return $this->subNodes;
248 * Read XML variables by calling readVariable() with 'general' as
251 * @param $key Key to read from
252 * @return $value Value from variable
254 public function readXmlData (string $key) {
255 // Is key parameter valid?
256 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: key=%s - CALLED!', $key));
259 throw new InvalidArgumentException('Parameter key is empty');
263 $value = parent::readVariable($key, 'general');
266 if (is_null($value)) {
267 // Bah, needs fixing.
268 $this->debugInstance(sprintf('[%s:%d]: key=%s returns NULL', __METHOD__, __LINE__, $key));
276 * Handles the template dependency for given XML node
278 * @param $node The XML node we should load a dependency template
279 * @param $templateDependency A template to load to satisfy dependencies
282 protected function handleTemplateDependency (string $node, string $templateDependency) {
283 // Check that the XML node is not empty
284 assert(!empty($node));
286 // Is the template dependency set?
287 if ((!empty($templateDependency)) && (!isset($this->dependencyContent[$node]))) {
288 // Get a temporay template instance
289 $templateInstance = XmlTemplateEngineFactory::createXmlTemplateEngineInstance($this->typePrefix . '_' . self::convertDashesToUnderscores($node) . '_' . $this->xmlTemplateType . '_template_class');
292 $templateInstance->loadXmlTemplate($templateDependency);
294 // Parse the XML content
295 $templateInstance->renderXmlContent();
297 // Save the parsed raw content in our dependency array
298 $this->dependencyContent[$node] = $templateInstance->getRawTemplateData();
303 * Handles the start element of an XML resource
305 * @param $resource XML parser resource (currently ignored)
306 * @param $element The element we shall handle
307 * @param $attributes All attributes
309 * @throws InvalidXmlNodeException If an unknown/invalid XML node name was found
311 public final function startElement ($resource, string $element, array $attributes) {
312 // Initial method name which will never be called...
313 $methodName = $this->initMethodName;
315 // Make the element name lower-case
316 $element = strtolower($element);
318 // Is the element a main node?
319 //* DEBUG: */ echo "START: >".$element."<<br />\n";
320 if (in_array($element, $this->getMainNodes())) {
321 // Okay, main node found!
322 $methodName = 'start' . StringUtils::convertToClassName($element);
325 $this->setCurrMainNode($element);
326 } elseif (in_array($element, $this->getSubNodes())) {
328 $methodName = 'start' . StringUtils::convertToClassName($element);
330 // Invalid node name found
331 throw new InvalidXmlNodeException(array($this, $element, $attributes), XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
335 call_user_func_array(array($this, $methodName), $attributes);
339 * Ends the main or sub node by sending out the gathered data
341 * @param $resource An XML resource pointer (currently ignored)
342 * @param $nodeName Name of the node we want to finish
344 * @throws XmlNodeMismatchException If current main node mismatches the closing one
346 public final function finishElement ($resource, string $nodeName) {
347 // Make all lower-case
348 $nodeName = strtolower($nodeName);
350 // Does this match with current main node?
351 //* DEBUG: */ echo "END: >".$nodeName."<<br />\n";
352 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
354 throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), XmlParser::EXCEPTION_XML_NODE_MISMATCH);
357 // Construct method name
358 $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
360 // Call the corresponding method
361 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
362 call_user_func_array(array($this, $methodName), array());
366 * Renders the given XML content
368 * @param $content Valid XML content or if not set the current loaded raw content
370 * @throws XmlParserException If an XML error was found
372 public function renderXmlContent (string $content = NULL) {
373 // Is the content set?
374 if (is_null($content)) {
375 // Get current content
376 $content = $this->getRawTemplateData();
379 // Get a XmlParser instance
380 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', [$this]);
382 // Check if XML compacting is enabled
383 if ($this->isXmlCompactingEnabled()) {
384 // Yes, so get a decorator class for transparent compacting
385 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
388 // Parse the XML document
389 $parserInstance->parseXmlContent($content);
393 * Enables or disables XML compacting
395 * @param $xmlCompacting New XML compacting setting
398 public final function enableXmlCompacting (bool $xmlCompacting = true) {
399 $this->xmlCompacting = $xmlCompacting;
403 * Checks whether XML compacting is enabled
405 * @return $xmlCompacting Whether XML compacting is enabled or disabled
407 public final function isXmlCompactingEnabled () {
408 return $this->xmlCompacting;