]> 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 = [
47                 'mail-data'
48         ];
49
50         /**
51          * Sub nodes in the XML tree
52          */
53         private $subNodes = [
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, string $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, string $nodeName) {
205                 // Does this match with current main node?
206                 //* DEBUG: */ echo "END: &gt;".$nodeName."&lt;<br />\n";
207                 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
208                         // Did not match!
209                         throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), Parseable::EXCEPTION_XML_NODE_MISMATCH);
210                 } elseif (in_array($nodeName, $this->getSubNodes())) {
211                         // Silently ignore sub nodes
212                         return;
213                 }
214
215                 // Construct method name
216                 $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
217
218                 // Call the corresponding method
219                 call_user_func_array(array($this, $methodName), []);
220         }
221
222         /**
223          * Adds the message text to the template engine
224          *
225          * @param       $resource               XML parser resource (currently ignored)
226          * @param       $characters             Characters to handle
227          * @return      void
228          */
229         public function characterHandler ($resource, string $characters) {
230                 // Trim all spaces away
231                 $characters = trim($characters);
232
233                 // Is this string empty?
234                 if (empty($characters)) {
235                         // Then skip it silently
236                         return;
237                 } // END - if
238
239                 // Add the message now
240                 $this->assignVariable('message', $characters);
241         }
242
243         /**
244          * Intializes the mail
245          *
246          * @return      void
247          * @todo        Add cache creation here
248          */
249         private function initEmail () {
250                 // Unfinished work!
251         }
252
253         /**
254          * Setter for mail data node
255          *
256          * @return      void
257          * @todo        Should we call back the mailer class here?
258          */
259         private function setEmailMailData () {
260                 // Set current main node
261                 $this->currMainNode = 'mail-data';
262         }
263
264         /**
265          * Setter for sender address property
266          *
267          * @param       $senderAddress  Sender address to set in email
268          * @return      void
269          */
270         private function setEmailPropertySenderAddress (string $senderAddress) {
271                 // Set the template variable
272                 $this->assignVariable('sender', $senderAddress);
273         }
274
275         /**
276          * Setter for recipient address property
277          *
278          * @param       $recipientAddress       Recipient address to set in email
279          * @return      void
280          */
281         private function setEmailPropertyRecipientAddress (string $recipientAddress) {
282                 // Set the template variable
283                 $this->assignVariable('recipient', $recipientAddress);
284         }
285
286         /**
287          * Setter for subject line property
288          *
289          * @return      void
290          */
291         private function setEmailPropertySubjectLine () {
292                 // Empty for now
293         }
294
295         /**
296          * Method stub to avoid output
297          *
298          * @return      void
299          */
300         private function setEmailPropertyMessage () {
301                 // Empty for now
302         }
303
304         /**
305          * Gets the template variable "message", stores it back as raw template data
306          * and compiles all variables so the mail message got prepared for output
307          *
308          * @return      void
309          */
310         private function finishMailData () {
311                 // Get the message and set it as new raw template data back
312                 $message = $this->readVariable('message');
313                 $this->setRawTemplateData($message);
314
315                 // Get some variables to compile
316                 //$sender = $this->compileRawCode($this->readVariable('sender'));
317                 //$this->assignVariable('sender', $sender);
318
319                 // Then compile all variables
320                 $this->compileVariables();
321         }
322
323         /**
324          * Invokes the final mail process
325          *
326          * @return      void
327          */
328         private function finishTextMail () {
329                 $this->getMailerInstance()->invokeMailDelivery();
330         }
331
332         /**
333          * Setter for mailer instance
334          *
335          * @param       $mailerInstance         A mailer instance
336          * @return      void
337          */
338         public final function setMailerInstance (DeliverableMail $mailerInstance) {
339                 $this->mailerInstance = $mailerInstance;
340         }
341
342         /**
343          * Getter for mailer instance
344          *
345          * @return      $mailerInstance         A mailer instance
346          */
347         protected final function getMailerInstance () {
348                 return $this->mailerInstance;
349         }
350
351         /**
352          * Outputs the mail to the world. This should only the mailer debug class do!
353          *
354          * @param       $responseInstance       An instance of a Responseable class
355          * @return      void
356          */
357         public function transferToResponse (Responseable $responseInstance) {
358                 $responseInstance->writeToBody($this->getCompiledData());
359         }
360
361 }