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