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