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\Filesystem\InvalidDirectoryException;
7 use Org\Mxchange\CoreFramework\Mailer\DeliverableMail;
8 use Org\Mxchange\CoreFramework\Parser\Xml\XmlParser;
9 use Org\Mxchange\CoreFramework\Registry\Registry;
10 use Org\Mxchange\CoreFramework\Response\Responseable;
11 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
12 use Org\Mxchange\CoreFramework\Template\Engine\BaseTemplateEngine;
13
14 // Import SPL stuff
15 use \UnexpectedValueException;
16
17 /**
18  * The own template engine for loading caching and sending out images
19  *
20  * @author              Roland Haeder <webmaster@shipsimu.org>
21  * @version             0.0.0
22  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
23  * @license             GNU GPL 3.0 or any newer version
24  * @link                http://www.shipsimu.org
25  * @todo                This template engine does not make use of setTemplateType()
26  *
27  * This program is free software: you can redistribute it and/or modify
28  * it under the terms of the GNU General Public License as published by
29  * the Free Software Foundation, either version 3 of the License, or
30  * (at your option) any later version.
31  *
32  * This program is distributed in the hope that it will be useful,
33  * but WITHOUT ANY WARRANTY; without even the implied warranty of
34  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
35  * GNU General Public License for more details.
36  *
37  * You should have received a copy of the GNU General Public License
38  * along with this program. If not, see <http://www.gnu.org/licenses/>.
39  */
40 class MailTemplateEngine extends BaseTemplateEngine implements CompileableTemplate {
41         /**
42          * Main nodes in the XML tree
43          */
44         private $mainNodes = array(
45                 'mail-data'
46         );
47
48         /**
49          * Sub nodes in the XML tree
50          */
51         private $subNodes = array(
52                 'subject-line',
53                 'sender-address',
54                 'recipient-address',
55                 'message'
56         );
57
58         /**
59          * Mailer instance
60          */
61         private $mailerInstance = NULL;
62
63         /**
64          * Current main node
65          */
66         private $currMainNode = '';
67
68         /**
69          * Protected constructor
70          *
71          * @return      void
72          */
73         protected function __construct () {
74                 // Call parent constructor
75                 parent::__construct(__CLASS__);
76         }
77
78         /**
79          * Creates an instance of the class TemplateEngine and prepares it for usage
80          *
81          * @return      $templateInstance               An instance of TemplateEngine
82          * @throws      UnexpectedValueException                If the provided $templateBasePath is empty or no string
83          * @throws      InvalidDirectoryException       If $templateBasePath is no
84          *                                                                                      directory or not found
85          * @throws      BasePathReadProtectedException  If $templateBasePath is
86          *                                                                                      read-protected
87          */
88         public static final function createMailTemplateEngine () {
89                 // Get a new instance
90                 $templateInstance = new MailTemplateEngine();
91
92                 // Get the application instance from registry
93                 $applicationInstance = Registry::getRegistry()->getInstance('app');
94
95                 // Determine base path
96                 $templateBasePath = $templateInstance->getConfigInstance()->getConfigEntry('application_base_path') . $applicationInstance->getAppShortName(). '/';
97
98                 // Is the base path valid?
99                 if (empty($templateBasePath)) {
100                         // Base path is empty
101                         throw new UnexpectedValueException(sprintf('[%s:%d] Variable templateBasePath is empty.', $templateInstance->__toString(), __LINE__), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
102                 } elseif (!is_string($templateBasePath)) {
103                         // Is not a string
104                         throw new UnexpectedValueException(sprintf('[%s:%d] %s is not a string with a base path.', $templateInstance->__toString(), __LINE__, $templateBasePath), self::EXCEPTION_INVALID_STRING);
105                 } elseif (!is_dir($templateBasePath)) {
106                         // Is not a path
107                         throw new InvalidDirectoryException(array($templateInstance, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
108                 } elseif (!is_readable($templateBasePath)) {
109                         // Is not readable
110                         throw new BasePathReadProtectedException(array($templateInstance, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
111                 }
112
113                 // Set the base path
114                 $templateInstance->setTemplateBasePath($templateBasePath);
115
116                 // Set template extensions
117                 $templateInstance->setRawTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('raw_template_extension'));
118                 $templateInstance->setCodeTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('code_template_extension'));
119
120                 // Absolute output path for compiled templates
121                 $templateInstance->setCompileOutputPath(sprintf('%s%s/',
122                         $templateBasePath,
123                         $templateInstance->getConfigInstance()->getConfigEntry('compile_output_path')
124                 ));
125
126                 // Return the prepared instance
127                 return $templateInstance;
128         }
129
130         /**
131          * Getter for current main node
132          *
133          * @return      $currMainNode   Current main node
134          */
135         public final function getCurrMainNode () {
136                 return $this->currMainNode;
137         }
138
139         /**
140          * Getter for main node array
141          *
142          * @return      $mainNodes      Array with valid main node names
143          */
144         public final function getMainNodes () {
145                 return $this->mainNodes;
146         }
147
148         /**
149          * Getter for sub node array
150          *
151          * @return      $subNodes       Array with valid sub node names
152          */
153         public final function getSubNodes () {
154                 return $this->subNodes;
155         }
156
157         /**
158          * Handles the start element of an XML resource
159          *
160          * @param       $resource               XML parser resource (currently ignored)
161          * @param       $element                The element we shall handle
162          * @param       $attributes             All attributes
163          * @return      void
164          * @throws      InvalidXmlNodeException         If an unknown/invalid XML node name was found
165          */
166         public function startElement ($resource, $element, array $attributes) {
167                 // Initial method name which will never be called...
168                 $methodName = 'initEmail';
169
170                 // Make the element name lower-case
171                 $element = strtolower($element);
172
173                 // Is the element a main node?
174                 //* DEBUG: */ echo "START: &gt;".$element."&lt;<br />\n";
175                 if (in_array($element, $this->getMainNodes())) {
176                         // Okay, main node found!
177                         $methodName = 'setEmail' . self::convertToClassName($element);
178                 } elseif (in_array($element, $this->getSubNodes())) {
179                         // Sub node found
180                         $methodName = 'setEmailProperty' . self::convertToClassName($element);
181                 } elseif ($element != 'text-mail') {
182                         // Invalid node name found
183                         throw new InvalidXmlNodeException(array($this, $element, $attributes), XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
184                 }
185
186                 // Call method
187                 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
188                 call_user_func_array(array($this, $methodName), $attributes);
189         }
190
191         /**
192          * Ends the main or sub node by sending out the gathered data
193          *
194          * @param       $resource       An XML resource pointer (currently ignored)
195          * @param       $nodeName       Name of the node we want to finish
196          * @return      void
197          * @throws      XmlNodeMismatchException        If current main node mismatches the closing one
198          */
199         public function finishElement ($resource, $nodeName) {
200                 // Make all lower-case
201                 $nodeName = strtolower($nodeName);
202
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()), XmlParser::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' . self::convertToClassName($nodeName);
215
216                 // Call the corresponding method
217                 call_user_func_array(array($this, $methodName), array());
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, $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                 } // END - if
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 ($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 ($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 }