]> git.mxchange.org Git - core.git/blob - framework/main/classes/template/mail/class_MailTemplateEngine.php
Continued:
[core.git] / framework / main / classes / template / mail / class_MailTemplateEngine.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Template\Engine;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Filesystem\InvalidDirectoryException;
8 use Org\Mxchange\CoreFramework\Mailer\DeliverableMail;
9 use Org\Mxchange\CoreFramework\Parser\Parseable;
10 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
11 use Org\Mxchange\CoreFramework\Response\Responseable;
12 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
13 use Org\Mxchange\CoreFramework\Template\Engine\BaseTemplateEngine;
14 use Org\Mxchange\CoreFramework\Utils\String\StringUtils;
15
16 // Import SPL stuff
17 use \UnexpectedValueException;
18
19 /**
20  * The own template engine for loading caching and sending out images
21  *
22  * @author              Roland Haeder <webmaster@shipsimu.org>
23  * @version             0.0.0
24  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
25  * @license             GNU GPL 3.0 or any newer version
26  * @link                http://www.shipsimu.org
27  * @todo                This template engine does not make use of setTemplateType()
28  *
29  * This program is free software: you can redistribute it and/or modify
30  * it under the terms of the GNU General Public License as published by
31  * the Free Software Foundation, either version 3 of the License, or
32  * (at your option) any later version.
33  *
34  * This program is distributed in the hope that it will be useful,
35  * but WITHOUT ANY WARRANTY; without even the implied warranty of
36  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37  * GNU General Public License for more details.
38  *
39  * You should have received a copy of the GNU General Public License
40  * along with this program. If not, see <http://www.gnu.org/licenses/>.
41  */
42 class MailTemplateEngine extends BaseTemplateEngine implements CompileableTemplate {
43         /**
44          * Main nodes in the XML tree
45          */
46         private $mainNodes = array(
47                 'mail-data'
48         );
49
50         /**
51          * Sub nodes in the XML tree
52          */
53         private $subNodes = array(
54                 'subject-line',
55                 'sender-address',
56                 'recipient-address',
57                 'message'
58         );
59
60         /**
61          * Mailer instance
62          */
63         private $mailerInstance = NULL;
64
65         /**
66          * Current main node
67          */
68         private $currMainNode = '';
69
70         /**
71          * Protected constructor
72          *
73          * @return      void
74          */
75         protected function __construct () {
76                 // Call parent constructor
77                 parent::__construct(__CLASS__);
78
79                 // Set template type
80                 $this->setTemplateType('mail');
81         }
82
83         /**
84          * Creates an instance of the class TemplateEngine and prepares it for usage
85          *
86          * @return      $templateInstance               An instance of TemplateEngine
87          * @throws      UnexpectedValueException                If the provided $templateBasePath is empty or no string
88          * @throws      InvalidDirectoryException       If $templateBasePath is no
89          *                                                                                      directory or not found
90          * @throws      BasePathReadProtectedException  If $templateBasePath is
91          *                                                                                      read-protected
92          */
93         public static final function createMailTemplateEngine () {
94                 // Get a new instance
95                 $templateInstance = new MailTemplateEngine();
96
97                 // Get the application instance from registry
98                 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
99
100                 // Determine base path
101                 $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . $applicationInstance->getAppShortName(). '/';
102
103                 // Is the base path valid?
104                 if (empty($templateBasePath)) {
105                         // Base path is empty
106                         throw new UnexpectedValueException(sprintf('[%s:%d] Variable templateBasePath is empty.', $templateInstance->__toString(), __LINE__), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
107                 } elseif (!is_string($templateBasePath)) {
108                         // Is not a string
109                         throw new UnexpectedValueException(sprintf('[%s:%d] %s is not a string with a base path.', $templateInstance->__toString(), __LINE__, $templateBasePath), self::EXCEPTION_INVALID_STRING);
110                 } elseif (!is_dir($templateBasePath)) {
111                         // Is not a path
112                         throw new InvalidDirectoryException(array($templateInstance, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
113                 } elseif (!is_readable($templateBasePath)) {
114                         // Is not readable
115                         throw new BasePathReadProtectedException(array($templateInstance, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
116                 }
117
118                 // Set the base path
119                 $templateInstance->setTemplateBasePath($templateBasePath);
120
121                 // Set template extensions
122                 $templateInstance->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
123                 $templateInstance->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_template_extension'));
124
125                 // Absolute output path for compiled templates
126                 $templateInstance->setCompileOutputPath(sprintf('%s%s/',
127                         $templateBasePath,
128                         FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
129                 ));
130
131                 // Return the prepared instance
132                 return $templateInstance;
133         }
134
135         /**
136          * Getter for current main node
137          *
138          * @return      $currMainNode   Current main node
139          */
140         public final function getCurrMainNode () {
141                 return $this->currMainNode;
142         }
143
144         /**
145          * Getter for main node array
146          *
147          * @return      $mainNodes      Array with valid main node names
148          */
149         public final function getMainNodes () {
150                 return $this->mainNodes;
151         }
152
153         /**
154          * Getter for sub node array
155          *
156          * @return      $subNodes       Array with valid sub node names
157          */
158         public final function getSubNodes () {
159                 return $this->subNodes;
160         }
161
162         /**
163          * Handles the start element of an XML resource
164          *
165          * @param       $resource               XML parser resource (currently ignored)
166          * @param       $element                The element we shall handle
167          * @param       $attributes             All attributes
168          * @return      void
169          * @throws      InvalidXmlNodeException         If an unknown/invalid XML node name was found
170          */
171         public function startElement ($resource, $element, array $attributes) {
172                 // Initial method name which will never be called...
173                 $methodName = 'initEmail';
174
175                 // Make the element name lower-case
176                 $element = strtolower($element);
177
178                 // Is the element a main node?
179                 //* DEBUG: */ echo "START: &gt;".$element."&lt;<br />\n";
180                 if (in_array($element, $this->getMainNodes())) {
181                         // Okay, main node found!
182                         $methodName = 'setEmail' . StringUtils::convertToClassName($element);
183                 } elseif (in_array($element, $this->getSubNodes())) {
184                         // Sub node found
185                         $methodName = 'setEmailProperty' . StringUtils::convertToClassName($element);
186                 } elseif ($element != 'text-mail') {
187                         // Invalid node name found
188                         throw new InvalidXmlNodeException(array($this, $element, $attributes), Parseable::EXCEPTION_XML_NODE_UNKNOWN);
189                 }
190
191                 // Call method
192                 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
193                 call_user_func_array(array($this, $methodName), $attributes);
194         }
195
196         /**
197          * Ends the main or sub node by sending out the gathered data
198          *
199          * @param       $resource       An XML resource pointer (currently ignored)
200          * @param       $nodeName       Name of the node we want to finish
201          * @return      void
202          * @throws      XmlNodeMismatchException        If current main node mismatches the closing one
203          */
204         public function finishElement ($resource, $nodeName) {
205                 // Make all lower-case
206                 $nodeName = strtolower($nodeName);
207
208                 // Does this match with current main node?
209                 //* DEBUG: */ echo "END: &gt;".$nodeName."&lt;<br />\n";
210                 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
211                         // Did not match!
212                         throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), Parseable::EXCEPTION_XML_NODE_MISMATCH);
213                 } elseif (in_array($nodeName, $this->getSubNodes())) {
214                         // Silently ignore sub nodes
215                         return;
216                 }
217
218                 // Construct method name
219                 $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
220
221                 // Call the corresponding method
222                 call_user_func_array(array($this, $methodName), []);
223         }
224
225         /**
226          * Adds the message text to the template engine
227          *
228          * @param       $resource               XML parser resource (currently ignored)
229          * @param       $characters             Characters to handle
230          * @return      void
231          */
232         public function characterHandler ($resource, $characters) {
233                 // Trim all spaces away
234                 $characters = trim($characters);
235
236                 // Is this string empty?
237                 if (empty($characters)) {
238                         // Then skip it silently
239                         return;
240                 } // END - if
241
242                 // Add the message now
243                 $this->assignVariable('message', $characters);
244         }
245
246         /**
247          * Intializes the mail
248          *
249          * @return      void
250          * @todo        Add cache creation here
251          */
252         private function initEmail () {
253                 // Unfinished work!
254         }
255
256         /**
257          * Setter for mail data node
258          *
259          * @return      void
260          * @todo        Should we call back the mailer class here?
261          */
262         private function setEmailMailData () {
263                 // Set current main node
264                 $this->currMainNode = 'mail-data';
265         }
266
267         /**
268          * Setter for sender address property
269          *
270          * @param       $senderAddress  Sender address to set in email
271          * @return      void
272          */
273         private function setEmailPropertySenderAddress ($senderAddress) {
274                 // Set the template variable
275                 $this->assignVariable('sender', $senderAddress);
276         }
277
278         /**
279          * Setter for recipient address property
280          *
281          * @param       $recipientAddress       Recipient address to set in email
282          * @return      void
283          */
284         private function setEmailPropertyRecipientAddress ($recipientAddress) {
285                 // Set the template variable
286                 $this->assignVariable('recipient', $recipientAddress);
287         }
288
289         /**
290          * Setter for subject line property
291          *
292          * @return      void
293          */
294         private function setEmailPropertySubjectLine () {
295                 // Empty for now
296         }
297
298         /**
299          * Method stub to avoid output
300          *
301          * @return      void
302          */
303         private function setEmailPropertyMessage () {
304                 // Empty for now
305         }
306
307         /**
308          * Gets the template variable "message", stores it back as raw template data
309          * and compiles all variables so the mail message got prepared for output
310          *
311          * @return      void
312          */
313         private function finishMailData () {
314                 // Get the message and set it as new raw template data back
315                 $message = $this->readVariable('message');
316                 $this->setRawTemplateData($message);
317
318                 // Get some variables to compile
319                 //$sender = $this->compileRawCode($this->readVariable('sender'));
320                 //$this->assignVariable('sender', $sender);
321
322                 // Then compile all variables
323                 $this->compileVariables();
324         }
325
326         /**
327          * Invokes the final mail process
328          *
329          * @return      void
330          */
331         private function finishTextMail () {
332                 $this->getMailerInstance()->invokeMailDelivery();
333         }
334
335         /**
336          * Setter for mailer instance
337          *
338          * @param       $mailerInstance         A mailer instance
339          * @return      void
340          */
341         public final function setMailerInstance (DeliverableMail $mailerInstance) {
342                 $this->mailerInstance = $mailerInstance;
343         }
344
345         /**
346          * Getter for mailer instance
347          *
348          * @return      $mailerInstance         A mailer instance
349          */
350         protected final function getMailerInstance () {
351                 return $this->mailerInstance;
352         }
353
354         /**
355          * Outputs the mail to the world. This should only the mailer debug class do!
356          *
357          * @param       $responseInstance       An instance of a Responseable class
358          * @return      void
359          */
360         public function transferToResponse (Responseable $responseInstance) {
361                 $responseInstance->writeToBody($this->getCompiledData());
362         }
363
364 }