* @version 0.0.0 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2018 Hub Developer Team * @license GNU GPL 3.0 or any newer version * @link http://www.shipsimu.org * @todo This template engine does not make use of setTemplateType() * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ abstract class BaseXmlTemplateEngine extends BaseTemplateEngine implements CompileableXmlTemplate { // Load traits use CompileableTemplateTrait; use StackableTrait; /** * Main nodes in the XML tree */ private $mainNodes = []; /** * Sub nodes in the XML tree */ private $subNodes = []; /** * Current main node */ private $curr = []; /** * XML template type */ private $xmlTemplateType = 'xml'; /** * Type prefix */ private $typePrefix = 'xml'; /** * Name of stacker */ private $stackerName = ''; /** * Content from dependency */ protected $dependencyContent = []; /** * XML compacting is disabled by default */ private $xmlCompacting = false; /** * Method name for XML template type */ private $initMethodName = 'invalid'; /** * Protected constructor * * @param $className Name of the class * @return void */ protected function __construct (string $className) { // Call parent constructor /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: className=%s - CONSTRUCTED!', $className)); parent::__construct($className); // Trace message /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!'); } /** * Does a generic initialization of the template engine * * @param $typePrefix Type prefix * @param $xmlTemplateType Type of XML template * @return $templateInstance An instance of TemplateEngine * @throws InvalidArgumentException If a parameter has an invalid value * @throws BasePathIsEmptyException If the provided $templateBasePath is empty * @throws InvalidBasePathStringException If $templateBasePath is no string * @throws BasePathIsNoDirectoryException If $templateBasePath is no * directory or not found * @throws BasePathReadProtectedException If $templateBasePath is * read-protected */ protected function initXmlTemplateEngine (string $typePrefix, string $xmlTemplateType) { // Check on parameter /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: typePrefix=%s,xmlTemplateType=%s - CALLED!', $typePrefix, $xmlTemplateType)); if (empty($typePrefix)) { // Throw IAE throw new InvalidArgumentException('Parameter "typePrefix" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); } elseif (empty($xmlTemplateType)) { // Throw IAE throw new InvalidArgumentException('Parameter "xmlTemplateType" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); } // Set XML template type and prefix $this->xmlTemplateType = $xmlTemplateType; $this->typePrefix = $typePrefix; $this->initMethodName = sprintf('init%s', StringUtils::convertToClassName($this->xmlTemplateType)); // Get template instance $applicationInstance = ApplicationHelper::getSelfInstance(); // Determine base path /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: applicationInstance=%s', $applicationInstance->__toString())); $templateBasePath = sprintf('%s%s%s', FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path'), FrameworkBootstrap::getRequestInstance()->getRequestElement('app'), DIRECTORY_SEPARATOR ); // Is the base path valid? /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: templateBasePath=%s', $templateBasePath)); if (empty($templateBasePath)) { // Base path is empty throw new BasePathIsEmptyException($this, self::EXCEPTION_UNEXPECTED_EMPTY_STRING); } elseif (!is_dir($templateBasePath)) { // Is not a path throw new BasePathIsNoDirectoryException(array($this, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME); } elseif (!is_readable($templateBasePath)) { // Is not readable throw new BasePathReadProtectedException(array($this, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH); } // Set the base path $this->setTemplateBasePath($templateBasePath); // Set template extensions $this->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension')); $this->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($typePrefix . '_message_template_extension')); // Absolute output path for compiled templates $this->setCompileOutputPath(sprintf('%s%s', $templateBasePath, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path') )); // Init a variable stacker $stackInstance = ObjectFactory::createObjectByConfiguredName($typePrefix . '_' . $xmlTemplateType . '_stacker_class'); // Set name $this->stackerName = $typePrefix . '_' . $xmlTemplateType; // Init stacker /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: this->stackerName=%s', $this->stackerName)); $stackInstance->initStack($this->stackerName); // Set it $this->setStackInstance($stackInstance); // Set it in main nodes /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Adding xmlTemplateType=%s to this->mainNodes ...', $xmlTemplateType)); array_push($this->mainNodes, str_replace('_', '-', $xmlTemplateType)); // Trace message /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!'); } /** * Load a specified XML template into the engine * * @param $templateName Optional name of template * @return void */ public function loadXmlTemplate (string $templateName = '') { // Is the template name empty? /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: templateName=%s - CALLED!', $templateName)); if (empty($templateName)) { // Set generic template name $templateName = $this->typePrefix . '_' . $this->xmlTemplateType . '_template_type'; } // Set template type /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: templateName=%s', $templateName)); $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($templateName)); // Load the special template /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Invoking this->loadTemplate(%s) ...', $this->xmlTemplateType)); $this->loadTemplate($this->xmlTemplateType); // Trace message /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!'); } /** * Getter for current main node * * @return $currMainNode Current main node */ public final function getCurrMainNode () { return $this->curr['main_node']; } /** * Setter for current main node * * @param $element Element name to set as current main node * @return $currMainNode Current main node */ private final function setCurrMainNode (string $element) { $this->curr['main_node'] = $element; } /** * Getter for main node array * * @return $mainNodes Array with valid main node names */ public final function getMainNodes () { return $this->mainNodes; } /** * Getter for stacker name * * @return $stackerName Name of stacker of this class */ protected final function getStackerName () { return $this->stackerName; } /** * Setter for sub node array * * @param $subNodes Array with valid sub node names * @return void */ public final function setSubNodes (array $subNodes) { $this->subNodes = $subNodes; } /** * Getter for sub node array * * @return $subNodes Array with valid sub node names */ public final function getSubNodes () { return $this->subNodes; } /** * Read XML variables by calling readVariable() with 'general' as * variable stack. * * @param $key Key to read from * @return $value Value from variable */ public function readXmlData (string $key) { // Is key parameter valid? /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: key=%s - CALLED!', $key)); if (empty($key)) { // Throw exception throw new InvalidArgumentException('Parameter key is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); } // Read the variable $value = parent::readVariable($key, 'general'); // Is this null? /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: value[]=%s', gettype($value))); if (is_null($value)) { // Bah, needs fixing. $this->debugInstance(sprintf('[%s:%d]: key=%s returns NULL', __METHOD__, __LINE__, $key)); } // Return value /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: value[%s]=%s - EXIT!', gettype($value), $value)); return $value; } /** * Handles the template dependency for given XML node * * @param $node The XML node we should load a dependency template * @param $templateDependency A template to load to satisfy dependencies * @return void * @throws InvalidArgumentException If a parameter has an invalid value */ protected function handleTemplateDependency (string $node, string $templateDependency) { // Check parameter /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: node=%s,templateDependency=%s - CALLED!', $node, $templateDependency)); if (empty($node)) { // Throw IAE throw new InvalidArgumentException('Parameter "node" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); } elseif (empty($templateDependency)) { // Throw IAE throw new InvalidArgumentException('Parameter "templateDependency" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); } // Is the template dependency set? /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: node=%s,templateDependency=%s', $node, $templateDependency)); if ((!empty($templateDependency)) && (!isset($this->dependencyContent[$node]))) { // Create class name $configKey = sprintf('%s_%s_%s_template_class', $this->typePrefix, self::convertDashesToUnderscores($node), $this->xmlTemplateType); // Get a temporay template instance /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: configKey=%s', $configKey)); $templateInstance = XmlTemplateEngineFactory::createXmlTemplateEngineInstance(); // Then load it /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: templateInstance=%s', $templateInstance->__toString())); $templateInstance->loadXmlTemplate($templateDependency); // Parse the XML content $templateInstance->renderXmlContent(); // Save the parsed raw content in our dependency array /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Invoking templateInstance->getRawTemplateData() for this->dependencyContent[%s] ...', $node)); $this->dependencyContent[$node] = $templateInstance->getRawTemplateData(); } // Trace message /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!'); } /** * Handles the start element of an XML resource * * @param $resource XML parser resource (currently ignored) * @param $element The element we shall handle * @param $attributes All attributes * @return void * @throws InvalidArgumentException If a parameter has an invalid value * @throws InvalidXmlNodeException If an unknown/invalid XML node name was found */ public final function startElement ($resource, string $element, array $attributes) { // Check parameters /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: resource[%s]=%s,element=%s,attributes()=%d - CALLED!', gettype($resource), $resource, $element, count($attributes))); if (!is_resource($resource)) { // Throw IAE throw new InvalidArgumentException(sprintf('Parameter resource has unexpected type %s', gettype($resource)), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); } elseif (empty($element)) { // Throw IAE throw new InvalidArgumentException('Parameter "element" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); } // Initial method name which will never be called... $methodName = $this->initMethodName; // Make the element name lower-case /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: methodName=%s', $methodName)); $element = strtolower($element); // Is the element a main node? /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: element=%s', $element)); if (in_array($element, $this->getMainNodes())) { // Okay, main node found! $methodName = 'start' . StringUtils::convertToClassName($element); // Set it $this->setCurrMainNode($element); } elseif (in_array($element, $this->getSubNodes())) { // Sub node found $methodName = 'start' . StringUtils::convertToClassName($element); } else { // Invalid node name found throw new InvalidXmlNodeException([$this, $element, $attributes], XmlParser::EXCEPTION_XML_NODE_UNKNOWN); } // Call method /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Invoking this->%s(attributes()=%d) ...', $methodName, count($attributes))); call_user_func_array([$this, $methodName], $attributes); // Trace message /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!'); } /** * Ends the main or sub node by sending out the gathered data * * @param $resource An XML resource pointer (currently ignored) * @param $nodeName Name of the node we want to finish * @return void * @throws XmlNodeMismatchException If current main node mismatches the closing one */ public final function finishElement ($resource, string $nodeName) { // Check parameters /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: resource[%s]=%s,nodeName=%s - CALLED!', gettype($resource), $resource, $nodeName)); if (!is_resource($resource)) { // Throw IAE throw new InvalidArgumentException(sprintf('Parameter resource has unexpected type %s', gettype($resource)), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); } elseif (empty($nodeName)) { // Throw IAE throw new InvalidArgumentException('Parameter "nodeName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); } // Make all lower-case $nodeName = strtolower($nodeName); // Does this match with current main node? /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: nodeName=%s', $nodeName)); if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) { // Did not match! throw new XmlNodeMismatchException ([$this, $nodeName, $this->getCurrMainNode()], XmlParser::EXCEPTION_XML_NODE_MISMATCH); } // Construct method name $methodName = 'finish' . StringUtils::convertToClassName($nodeName); // Call the corresponding method /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Invoking this->%s() ...', $methodName)); call_user_func_array([$this, $methodName], []); // Trace message /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!'); } /** * Renders the given XML content * * @param $content Valid XML content or if not set the current loaded raw content * @return void * @throws InvalidArgumentException If a parameter has an invalid value */ public function renderXmlContent (string $content = NULL) { // Is the content set? /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: content[%s]()=%d - CALLED!', gettype($content), strlen($content))); if (is_null($content)) { // Get current content $content = $this->getRawTemplateData(); } elseif (empty($content)) { // Throw IAE throw new InvalidArgumentException('Parameter "content" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); } // Get a XmlParser instance $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', [$this]); // Check if XML compacting is enabled /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: parserInstance=%s', $parserInstance->__toString())); if ($this->isXmlCompactingEnabled()) { // Yes, so get a decorator class for transparent compacting $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', [$parserInstance]); } // Parse the XML document /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Invoking parserInstance->parseXmlContent(content()=%d) ...', strlen($content))); $parserInstance->parseXmlContent($content); // Trace message /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!'); } /** * Enables or disables XML compacting * * @param $xmlCompacting New XML compacting setting * @return void */ public final function enableXmlCompacting (bool $xmlCompacting = true) { $this->xmlCompacting = $xmlCompacting; } /** * Checks whether XML compacting is enabled * * @return $xmlCompacting Whether XML compacting is enabled or disabled */ public final function isXmlCompactingEnabled () { return $this->xmlCompacting; } }