]> 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\Xml\XmlParser;
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
80         /**
81          * Creates an instance of the class TemplateEngine and prepares it for usage
82          *
83          * @return      $templateInstance               An instance of TemplateEngine
84          * @throws      UnexpectedValueException                If the provided $templateBasePath is empty or no string
85          * @throws      InvalidDirectoryException       If $templateBasePath is no
86          *                                                                                      directory or not found
87          * @throws      BasePathReadProtectedException  If $templateBasePath is
88          *                                                                                      read-protected
89          */
90         public static final function createMailTemplateEngine () {
91                 // Get a new instance
92                 $templateInstance = new MailTemplateEngine();
93
94                 // Get the application instance from registry
95                 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
96
97                 // Determine base path
98                 $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . $applicationInstance->getAppShortName(). '/';
99
100                 // Is the base path valid?
101                 if (empty($templateBasePath)) {
102                         // Base path is empty
103                         throw new UnexpectedValueException(sprintf('[%s:%d] Variable templateBasePath is empty.', $templateInstance->__toString(), __LINE__), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
104                 } elseif (!is_string($templateBasePath)) {
105                         // Is not a string
106                         throw new UnexpectedValueException(sprintf('[%s:%d] %s is not a string with a base path.', $templateInstance->__toString(), __LINE__, $templateBasePath), self::EXCEPTION_INVALID_STRING);
107                 } elseif (!is_dir($templateBasePath)) {
108                         // Is not a path
109                         throw new InvalidDirectoryException(array($templateInstance, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
110                 } elseif (!is_readable($templateBasePath)) {
111                         // Is not readable
112                         throw new BasePathReadProtectedException(array($templateInstance, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
113                 }
114
115                 // Set the base path
116                 $templateInstance->setTemplateBasePath($templateBasePath);
117
118                 // Set template extensions
119                 $templateInstance->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
120                 $templateInstance->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_template_extension'));
121
122                 // Absolute output path for compiled templates
123                 $templateInstance->setCompileOutputPath(sprintf('%s%s/',
124                         $templateBasePath,
125                         FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
126                 ));
127
128                 // Return the prepared instance
129                 return $templateInstance;
130         }
131
132         /**
133          * Getter for current main node
134          *
135          * @return      $currMainNode   Current main node
136          */
137         public final function getCurrMainNode () {
138                 return $this->currMainNode;
139         }
140
141         /**
142          * Getter for main node array
143          *
144          * @return      $mainNodes      Array with valid main node names
145          */
146         public final function getMainNodes () {
147                 return $this->mainNodes;
148         }
149
150         /**
151          * Getter for sub node array
152          *
153          * @return      $subNodes       Array with valid sub node names
154          */
155         public final function getSubNodes () {
156                 return $this->subNodes;
157         }
158
159         /**
160          * Handles the start element of an XML resource
161          *
162          * @param       $resource               XML parser resource (currently ignored)
163          * @param       $element                The element we shall handle
164          * @param       $attributes             All attributes
165          * @return      void
166          * @throws      InvalidXmlNodeException         If an unknown/invalid XML node name was found
167          */
168         public function startElement ($resource, $element, array $attributes) {
169                 // Initial method name which will never be called...
170                 $methodName = 'initEmail';
171
172                 // Make the element name lower-case
173                 $element = strtolower($element);
174
175                 // Is the element a main node?
176                 //* DEBUG: */ echo "START: &gt;".$element."&lt;<br />\n";
177                 if (in_array($element, $this->getMainNodes())) {
178                         // Okay, main node found!
179                         $methodName = 'setEmail' . StringUtils::convertToClassName($element);
180                 } elseif (in_array($element, $this->getSubNodes())) {
181                         // Sub node found
182                         $methodName = 'setEmailProperty' . StringUtils::convertToClassName($element);
183                 } elseif ($element != 'text-mail') {
184                         // Invalid node name found
185                         throw new InvalidXmlNodeException(array($this, $element, $attributes), XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
186                 }
187
188                 // Call method
189                 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
190                 call_user_func_array(array($this, $methodName), $attributes);
191         }
192
193         /**
194          * Ends the main or sub node by sending out the gathered data
195          *
196          * @param       $resource       An XML resource pointer (currently ignored)
197          * @param       $nodeName       Name of the node we want to finish
198          * @return      void
199          * @throws      XmlNodeMismatchException        If current main node mismatches the closing one
200          */
201         public function finishElement ($resource, $nodeName) {
202                 // Make all lower-case
203                 $nodeName = strtolower($nodeName);
204
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()), XmlParser::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), array());
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, $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 ($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 ($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 }