Even more conflicting calls fixed
[shipsimu.git] / inc / classes / main / template / image / class_ImageTemplateEngine.php
1 <?php
2 /**
3  * The own template engine for loading caching and sending out images
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, this is free software
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <http://www.gnu.org/licenses/>.
23  */
24 class ImageTemplateEngine extends BaseTemplateEngine implements CompileableTemplate {
25         /**
26          * Main nodes in the XML tree ('image' is ignored)
27          */
28         private $mainNodes = array("base", "type", "resolution", "background-color", "foreground-color", "image-string");
29
30         /**
31          * Sub nodes in the XML tree
32          */
33         private $subNodes = array("name", "string-name", "x", "y", "font-size", "width", "height", "red", "green", "blue", "text");
34
35         /**
36          * Image instance
37          */
38         private $imageInstance = null;
39
40         /**
41          * Current main node
42          */
43         private $currMainNode = "";
44
45         /**
46          * Protected constructor
47          *
48          * @return      void
49          */
50         protected function __construct () {
51                 // Call parent constructor
52                 parent::__construct(__CLASS__);
53
54                 // Set part description
55                 $this->setObjectDescription("Image template engine");
56
57                 // Create unique ID number
58                 $this->generateUniqueId();
59         }
60
61         /**
62          * Creates an instance of the class TemplateEngine and prepares it for usage
63          *
64          * @param       $basePath               The local base path for all templates
65          * @param       $langInstance   An instance of LanguageSystem (default)
66          * @param       $ioInstance             An instance of FileIoHandler (default, middleware!)
67          * @return      $tplInstance    An instance of TemplateEngine
68          * @throws      BasePathIsEmptyException                If the provided $basePath is empty
69          * @throws      InvalidBasePathStringException  If $basePath is no string
70          * @throws      BasePathIsNoDirectoryException  If $basePath is no
71          *                                                                                      directory or not found
72          * @throws      BasePathReadProtectedException  If $basePath is
73          *                                                                                      read-protected
74          */
75         public final static function createImageTemplateEngine ($basePath, ManageableLanguage  $langInstance, FileIoHandler $ioInstance) {
76                 // Get a new instance
77                 $tplInstance = new ImageTemplateEngine();
78
79                 // Is the base path valid?
80                 if (empty($basePath)) {
81                         // Base path is empty
82                         throw new BasePathIsEmptyException($tplInstance, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
83                 } elseif (!is_string($basePath)) {
84                         // Is not a string
85                         throw new InvalidBasePathStringException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_STRING);
86                 } elseif (!is_dir($basePath)) {
87                         // Is not a path
88                         throw new BasePathIsNoDirectoryException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_PATH_NAME);
89                 } elseif (!is_readable($basePath)) {
90                         // Is not readable
91                         throw new BasePathReadProtectedException(array($tplInstance, $basePath), self::EXCEPTION_READ_PROTECED_PATH);
92                 }
93
94                 // Get configuration instance
95                 $cfgInstance = FrameworkConfiguration::getInstance();
96
97                 // Set the base path
98                 $tplInstance->setBasePath($basePath);
99
100                 // Set the language and IO instances
101                 $tplInstance->setLanguageInstance($langInstance);
102                 $tplInstance->setFileIoInstance($ioInstance);
103
104                 // Set template extensions
105                 $tplInstance->setRawTemplateExtension($cfgInstance->readConfig('raw_template_extension'));
106                 $tplInstance->setCodeTemplateExtension($cfgInstance->readConfig('code_template_extension'));
107
108                 // Absolute output path for compiled templates
109                 $tplInstance->setCompileOutputPath(PATH . $cfgInstance->readConfig('compile_output_path'));
110
111                 // Return the prepared instance
112                 return $tplInstance;
113         }
114
115         /**
116          * Renders the given image content
117          *
118          * @param       $imageContent           A valid XML image content
119          * @return      void
120          * @throws      XmlParserException      If an XML error was found
121          */
122         public function renderImageContent ($imageContent) {
123                 // Get an XML parser
124                 $xmlParser = xml_parser_create();
125
126                 // Force case-folding to on
127                 xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, true);
128
129                 // Set object
130                 xml_set_object($xmlParser, $this);
131
132                 // Set handler call-backs
133                 xml_set_element_handler($xmlParser, 'startElement', 'endElement');
134                 xml_set_character_data_handler($xmlParser, 'characterHandler');
135
136                 // Now parse the XML tree
137                 if (!xml_parse($xmlParser, $imageContent)) {
138                         // Error found in XML!
139                         throw new XmlParserException(array($this, $xmlParser), BaseHelper::EXCEPTION_XML_PARSER_ERROR);
140                 } // END - if
141
142                 // Free the parser
143                 xml_parser_free($xmlParser);
144         }
145
146         /**
147          * Handles the start element of an XML resource
148          *
149          * @param       $resource               XML parser resource (currently ignored)
150          * @param       $element                The element we shall handle
151          * @param       $attributes             All attributes
152          * @return      void
153          * @throws      InvalidXmlNodeException         If an unknown/invalid XML node name was found
154          */
155         public function startElement ($resource, $element, array $attributes) {
156                 // Initial method name which will never be called...
157                 $methodName = 'initImage';
158
159                 // Make the element name lower-case
160                 $element = strtolower($element);
161
162                 // Is the element a main node?
163                 //* DEBUG: */ echo "START: &gt;".$element."&lt;<br />\n";
164                 if (in_array($element, $this->mainNodes)) {
165                         // Okay, main node found!
166                         $methodName = 'setImage' . $this->convertToClassName($element);
167                 } elseif (in_array($element, $this->subNodes)) {
168                         // Sub node found
169                         $methodName = 'setImageProperty' . $this->convertToClassName($element);
170                 } elseif ($element != 'image') {
171                         // Invalid node name found
172                         throw new InvalidXmlNodeException(array($this, $element, $attributes), BaseHelper::EXCEPTION_XML_NODE_UNKNOWN);
173                 }
174
175                 // Call method
176                 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
177                 call_user_func_array(array($this, $methodName), $attributes);
178         }
179
180         /**
181          * Ends the main or sub node by sending out the gathered data
182          *
183          * @param       $resource       An XML resource pointer (currently ignored)
184          * @param       $nodeName       Name of the node we want to finish
185          * @return      void
186          * @throws      XmlNodeMismatchException        If current main node mismatches the closing one
187          */
188         public function endElement ($resource, $nodeName) {
189                 // Make all lower-case
190                 $nodeName = strtolower($nodeName);
191
192                 // Does this match with current main node?
193                 //* DEBUG: */ echo "END: &gt;".$nodeName."&lt;<br />\n";
194                 if (($nodeName != $this->currMainNode) && (in_array($nodeName, $this->mainNodes))) {
195                         // Did not match!
196                         throw new XmlNodeMismatchException (array($this, $nodeName, $this->currMainNode), BaseHelper::EXCEPTION_XML_NODE_MISMATCH);
197                 } elseif (in_array($nodeName, $this->subNodes)) {
198                         // Silently ignore sub nodes
199                         return;
200                 }
201
202                 // Construct method name
203                 $methodName = 'finish' . $this->convertToClassName($nodeName);
204
205                 // Call the corresponding method
206                 call_user_func_array(array($this->imageInstance, $methodName), array());
207         }
208
209         /**
210          * Currently not used
211          *
212          * @param       $resource               XML parser resource (currently ignored)
213          * @param       $characters             Characters to handle
214          * @return      void
215          * @todo        Find something usefull with this!
216          */
217         public function characterHandler ($resource, $characters) {
218                 // Trim all spaces away
219                 $characters = trim($characters);
220
221                 // Is this string empty?
222                 if (empty($characters)) {
223                         // Then skip it silently
224                         return false;
225                 } // END - if
226
227                 // Unfinished work!
228                 $this->partialStub("Handling extra characters is not yet supported!");
229         }
230
231         /**
232          * Intializes the image
233          *
234          * @return      void
235          * @todo        Add cache creation here
236          */
237         private function initImage () {
238                 // Unfinished work!
239         }
240
241         /**
242          * Set the image type
243          *
244          * @param       $imageType      Code fragment or direct value holding the image type
245          * @return      void
246          */
247         private function setImageType ($imageType) {
248                 // Set group to general
249                 $this->setVariableGroup('general');
250
251                 // Try to compile it first to get the value from variable stack
252                 $imageType = $this->compileRawCode($imageType);
253
254                 // Now make a class name of it
255                 $className = $this->convertToClassName($imageType.'_image');
256
257                 // And try to initiate it
258                 $this->imageInstance = ObjectFactory::createObjectByName($className, array($this));
259
260                 // Set current main node to type
261                 $this->currMainNode = 'type';
262         }
263
264         /**
265          * "Setter" for resolution, we first need to collect the resolution from the
266          * sub-nodes. So first, this method will prepare an array for it
267          *
268          * @return      void
269          */
270         private function setImageResolution () {
271                 // Call the image class
272                 $this->imageInstance->initResolution();
273
274                 // Current main node is resolution
275                 $this->currMainNode = 'resolution';
276         }
277
278         /**
279          * "Setter" for base information. For more details see above method!
280          *
281          * @return      void
282          * @see         ImageTemplateEngine::setImageResolution
283          */
284         private function setImageBase () {
285                 // Call the image class
286                 $this->imageInstance->initBase();
287
288                 // Current main node is resolution
289                 $this->currMainNode = 'base';
290         }
291
292         /**
293          * "Setter" for background-color. For more details see above method!
294          *
295          * @return      void
296          * @see         ImageTemplateEngine::setImageResolution
297          */
298         private function setImageBackgroundColor () {
299                 // Call the image class
300                 $this->imageInstance->initBackgroundColor();
301
302                 // Current main node is background-color
303                 $this->currMainNode = 'background-color';
304         }
305
306         /**
307          * "Setter" for foreground-color. For more details see above method!
308          *
309          * @return      void
310          * @see         ImageTemplateEngine::setImageResolution
311          */
312         private function setImageForegroundColor () {
313                 // Call the image class
314                 $this->imageInstance->initForegroundColor();
315
316                 // Current main node is foreground-color
317                 $this->currMainNode = 'foreground-color';
318         }
319
320         /**
321          * "Setter" for image-string. For more details see above method!
322          *
323          * @param       $groupable      Wether this image string is groupable
324          * @return      void
325          * @see         ImageTemplateEngine::setImageResolution
326          */
327         private function setImageImageString ($groupable = 'single') {
328                 // Call the image class
329                 $this->imageInstance->initImageString($groupable);
330
331                 // Current main node is foreground-color
332                 $this->currMainNode = 'image-string';
333         }
334
335         /**
336          * Setter for image name
337          *
338          * @param       $imageName      Name of the image
339          * @return      void
340          */
341         private function setImagePropertyName ($imageName) {
342                 // Call the image class
343                 $this->imageInstance->setImageName($imageName);
344         }
345
346         /**
347          * Setter for image width
348          *
349          * @param       $width  Width of the image or variable
350          * @return      void
351          */
352         private function setImagePropertyWidth ($width) {
353                 // Call the image class
354                 $this->imageInstance->setWidth($width);
355         }
356
357         /**
358          * Setter for image height
359          *
360          * @param       $height Height of the image or variable
361          * @return      void
362          */
363         private function setImagePropertyHeight ($height) {
364                 // Call the image class
365                 $this->imageInstance->setHeight($height);
366         }
367
368         /**
369          * Setter for image red color
370          *
371          * @param       $red    Red color value
372          * @return      void
373          */
374         private function setImagePropertyRed ($red) {
375                 // Call the image class
376                 $this->imageInstance->setRed($red);
377         }
378
379         /**
380          * Setter for image green color
381          *
382          * @param       $green  Green color value
383          * @return      void
384          */
385         private function setImagePropertyGreen ($green) {
386                 // Call the image class
387                 $this->imageInstance->setGreen($green);
388         }
389
390         /**
391          * Setter for image blue color
392          *
393          * @param       $blue   Blue color value
394          * @return      void
395          */
396         private function setImagePropertyBlue ($blue) {
397                 // Call the image class
398                 $this->imageInstance->setBlue($blue);
399         }
400
401         /**
402          * Setter for string name (identifier)
403          *
404          * @param       $stringName             String name (identifier)
405          * @return      void
406          */
407         private function setImagePropertyStringName ($stringName) {
408                 // Call the image class
409                 $this->imageInstance->setStringName($stringName);
410         }
411
412         /**
413          * Setter for font size
414          *
415          * @param       $fontSize       Size of the font
416          * @return      void
417          */
418         private function setImagePropertyFontSize ($fontSize) {
419                 // Call the image class
420                 $this->imageInstance->setFontSize($fontSize);
421         }
422
423         /**
424          * Setter for image string
425          *
426          * @param       $imageString    Image string to set
427          * @return      void
428          */
429         private function setImagePropertyText ($imageString) {
430                 // Call the image class
431                 $this->imageInstance->setString($imageString);
432         }
433
434         /**
435          * Setter for X coordinate
436          *
437          * @param       $x      X coordinate
438          * @return      void
439          */
440         private function setImagePropertyX ($x) {
441                 // Call the image class
442                 $this->imageInstance->setX($x);
443         }
444
445         /**
446          * Setter for Y coordinate
447          *
448          * @param       $y      Y coordinate
449          * @return      void
450          */
451         private function setImagePropertyY ($y) {
452                 // Call the image class
453                 $this->imageInstance->setY($y);
454         }
455
456         /**
457          * Getter for image cache file (FQFN)
458          *
459          * @return      $fqfn   Full-qualified file name of the image cache
460          */
461         public function getImageCacheFqfn () {
462                 // Get the FQFN ready
463                 $fqfn = $this->getBasePath().'_cache/' . md5($this->imageInstance->getImageName().":".$this->__toString().":".$this->imageInstance->__toString()) . "." . $this->imageInstance->getImageType();
464
465                 // Return it
466                 return $fqfn;
467         }
468
469         /**
470          * Outputs the image to the world
471          *
472          * @param       $responseInstance       An instance of a Responseable class
473          * @return      void
474          */
475         public function transferToResponse (Responseable $responseInstance) {
476                 // Set the image instance
477                 $responseInstance->setImageInstance($this->imageInstance);
478         }
479 }
480
481 // [EOF]
482 ?>