]> 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\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\Response\Responseable;
13 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
14 use Org\Mxchange\CoreFramework\Template\Engine\BaseTemplateEngine;
15 use Org\Mxchange\CoreFramework\Utils\Strings\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 - 2023 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         private 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__), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
108                 } elseif (!is_dir($templateBasePath)) {
109                         // Is not a path
110                         throw new InvalidDirectoryException(array($templateInstance, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
111                 } elseif (!is_readable($templateBasePath)) {
112                         // Is not readable
113                         throw new BasePathReadProtectedException(array($templateInstance, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
114                 }
115
116                 // Set the base path
117                 $templateInstance->setTemplateBasePath($templateBasePath);
118
119                 // Set template extensions
120                 $templateInstance->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
121                 $templateInstance->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_template_extension'));
122
123                 // Absolute output path for compiled templates
124                 $templateInstance->setCompileOutputPath(sprintf('%s%s/',
125                         $templateBasePath,
126                         FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
127                 ));
128
129                 // Return the prepared instance
130                 return $templateInstance;
131         }
132
133         /**
134          * Getter for current main node
135          *
136          * @return      $currMainNode   Current main node
137          */
138         public final function getCurrMainNode () {
139                 return $this->currMainNode;
140         }
141
142         /**
143          * Getter for main node array
144          *
145          * @return      $mainNodes      Array with valid main node names
146          */
147         public final function getMainNodes () {
148                 return $this->mainNodes;
149         }
150
151         /**
152          * Getter for sub node array
153          *
154          * @return      $subNodes       Array with valid sub node names
155          */
156         public final function getSubNodes () {
157                 return $this->subNodes;
158         }
159
160         /**
161          * Handles the start element of an XML resource
162          *
163          * @param       $resource               XML parser resource (currently ignored)
164          * @param       $element                The element we shall handle
165          * @param       $attributes             All attributes
166          * @return      void
167          * @throws      InvalidXmlNodeException         If an unknown/invalid XML node name was found
168          */
169         public function startElement ($resource, string $element, array $attributes) {
170                 // Initial method name which will never be called...
171                 $methodName = 'initEmail';
172
173                 // Make the element name lower-case
174                 $element = strtolower($element);
175
176                 // Is the element a main node?
177                 //* DEBUG: */ echo "START: &gt;".$element."&lt;<br />\n";
178                 if (in_array($element, $this->getMainNodes())) {
179                         // Okay, main node found!
180                         $methodName = 'setEmail' . StringUtils::convertToClassName($element);
181                 } elseif (in_array($element, $this->getSubNodes())) {
182                         // Sub node found
183                         $methodName = 'setEmailProperty' . StringUtils::convertToClassName($element);
184                 } elseif ($element != 'text-mail') {
185                         // Invalid node name found
186                         throw new InvalidXmlNodeException([$this, $element, $attributes], Parseable::EXCEPTION_XML_NODE_UNKNOWN);
187                 }
188
189                 // Call method
190                 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
191                 call_user_func_array(array($this, $methodName), $attributes);
192         }
193
194         /**
195          * Ends the main or sub node by sending out the gathered data
196          *
197          * @param       $resource       An XML resource pointer (currently ignored)
198          * @param       $nodeName       Name of the node we want to finish
199          * @return      void
200          * @throws      XmlNodeMismatchException        If current main node mismatches the closing one
201          */
202         public function finishElement ($resource, string $nodeName) {
203                 // Does this match with current main node?
204                 //* DEBUG: */ echo "END: &gt;".$nodeName."&lt;<br />\n";
205                 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
206                         // Did not match!
207                         throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), Parseable::EXCEPTION_XML_NODE_MISMATCH);
208                 } elseif (in_array($nodeName, $this->getSubNodes())) {
209                         // Silently ignore sub nodes
210                         return;
211                 }
212
213                 // Construct method name
214                 $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
215
216                 // Call the corresponding method
217                 call_user_func_array(array($this, $methodName), []);
218         }
219
220         /**
221          * Adds the message text to the template engine
222          *
223          * @param       $resource               XML parser resource (currently ignored)
224          * @param       $characters             Characters to handle
225          * @return      void
226          */
227         public function characterHandler ($resource, string $characters) {
228                 // Trim all spaces away
229                 $characters = trim($characters);
230
231                 // Is this string empty?
232                 if (empty($characters)) {
233                         // Then skip it silently
234                         return;
235                 }
236
237                 // Add the message now
238                 $this->assignVariable('message', $characters);
239         }
240
241         /**
242          * Intializes the mail
243          *
244          * @return      void
245          * @todo        Add cache creation here
246          */
247         private function initEmail () {
248                 // Unfinished work!
249         }
250
251         /**
252          * Setter for mail data node
253          *
254          * @return      void
255          * @todo        Should we call back the mailer class here?
256          */
257         private function setEmailMailData () {
258                 // Set current main node
259                 $this->currMainNode = 'mail-data';
260         }
261
262         /**
263          * Setter for sender address property
264          *
265          * @param       $senderAddress  Sender address to set in email
266          * @return      void
267          */
268         private function setEmailPropertySenderAddress (string $senderAddress) {
269                 // Set the template variable
270                 $this->assignVariable('sender', $senderAddress);
271         }
272
273         /**
274          * Setter for recipient address property
275          *
276          * @param       $recipientAddress       Recipient address to set in email
277          * @return      void
278          */
279         private function setEmailPropertyRecipientAddress (string $recipientAddress) {
280                 // Set the template variable
281                 $this->assignVariable('recipient', $recipientAddress);
282         }
283
284         /**
285          * Setter for subject line property
286          *
287          * @return      void
288          */
289         private function setEmailPropertySubjectLine () {
290                 // Empty for now
291         }
292
293         /**
294          * Method stub to avoid output
295          *
296          * @return      void
297          */
298         private function setEmailPropertyMessage () {
299                 // Empty for now
300         }
301
302         /**
303          * Gets the template variable "message", stores it back as raw template data
304          * and compiles all variables so the mail message got prepared for output
305          *
306          * @return      void
307          */
308         private function finishMailData () {
309                 // Get the message and set it as new raw template data back
310                 $message = $this->readVariable('message');
311                 $this->setRawTemplateData($message);
312
313                 // Get some variables to compile
314                 //$sender = $this->compileRawCode($this->readVariable('sender'));
315                 //$this->assignVariable('sender', $sender);
316
317                 // Then compile all variables
318                 $this->compileVariables();
319         }
320
321         /**
322          * Invokes the final mail process
323          *
324          * @return      void
325          */
326         private function finishTextMail () {
327                 $this->getMailerInstance()->invokeMailDelivery();
328         }
329
330         /**
331          * Setter for mailer instance
332          *
333          * @param       $mailerInstance         A mailer instance
334          * @return      void
335          */
336         public final function setMailerInstance (DeliverableMail $mailerInstance) {
337                 $this->mailerInstance = $mailerInstance;
338         }
339
340         /**
341          * Getter for mailer instance
342          *
343          * @return      $mailerInstance         A mailer instance
344          */
345         protected final function getMailerInstance () {
346                 return $this->mailerInstance;
347         }
348
349         /**
350          * Outputs the mail to the world. This should only the mailer debug class do!
351          *
352          * @param       $responseInstance       An instance of a Responseable class
353          * @return      void
354          */
355         public function transferToResponse (Responseable $responseInstance) {
356                 $responseInstance->writeToBody($this->getCompiledData());
357         }
358
359 }