19fc4848546bb3c2ac7476c9edbc84b3e20e4e55
[core.git] / framework / main / classes / template / image / class_ImageTemplateEngine.php
1 <?php
2 // Own namespace
3 namespace CoreFramework\Template\Engine;
4
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7 use CoreFramework\Filesystem\InvalidDirectoryException;
8 use CoreFramework\Parser\Xml\XmlParser;
9 use CoreFramework\Registry\Registry;
10 use CoreFramework\Response\Responseable;
11 use CoreFramework\Template\CompileableTemplate;
12 use 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  *
26  * This program is free software: you can redistribute it and/or modify
27  * it under the terms of the GNU General Public License as published by
28  * the Free Software Foundation, either version 3 of the License, or
29  * (at your option) any later version.
30  *
31  * This program is distributed in the hope that it will be useful,
32  * but WITHOUT ANY WARRANTY; without even the implied warranty of
33  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
34  * GNU General Public License for more details.
35  *
36  * You should have received a copy of the GNU General Public License
37  * along with this program. If not, see <http://www.gnu.org/licenses/>.
38  */
39 class ImageTemplateEngine extends BaseTemplateEngine implements CompileableTemplate {
40         /**
41          * Main nodes in the XML tree ('image' is ignored)
42          */
43         private $mainNodes = array(
44                 'base',
45                 'type',
46                 'resolution',
47                 'background-color',
48                 'foreground-color',
49                 'image-string'
50         );
51
52         /**
53          * Sub nodes in the XML tree
54          */
55         private $subNodes = array(
56                 'name',
57                 'string-name',
58                 'x',
59                 'y',
60                 'font-size',
61                 'width',
62                 'height',
63                 'red',
64                 'green',
65                 'blue',
66                 'text'
67         );
68
69         /**
70          * Current main node
71          */
72         private $currMainNode = '';
73
74         /**
75          * Protected constructor
76          *
77          * @return      void
78          */
79         protected function __construct () {
80                 // Call parent constructor
81                 parent::__construct(__CLASS__);
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 createImageTemplateEngine () {
95                 // Get a new instance
96                 $templateInstance = new ImageTemplateEngine();
97
98                 // Get the application instance from registry
99                 $applicationInstance = Registry::getRegistry()->getInstance('app');
100
101                 // Determine base path
102                 $templateBasePath = $templateInstance->getConfigInstance()->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__), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
108                 } elseif (!is_string($templateBasePath)) {
109                         // Is not a string
110                         throw new UnexpectedValueException(sprintf('[%s:%d] %s is not a string with a base path.', $templateInstance->__toString(), __LINE__, $templateBasePath), self::EXCEPTION_INVALID_STRING);
111                 } elseif (!is_dir($templateBasePath)) {
112                         // Is not a path
113                         throw new InvalidDirectoryException(array($templateInstance, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
114                 } elseif (!is_readable($templateBasePath)) {
115                         // Is not readable
116                         throw new BasePathReadProtectedException(array($templateInstance, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
117                 }
118
119                 // Set the base path
120                 $templateInstance->setTemplateBasePath($templateBasePath);
121
122                 // Set template extensions
123                 $templateInstance->setRawTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('raw_template_extension'));
124                 $templateInstance->setCodeTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('code_template_extension'));
125
126                 // Absolute output path for compiled templates
127                 $templateInstance->setCompileOutputPath(sprintf('%s%s/',
128                         $templateBasePath,
129                         $templateInstance->getConfigInstance()->getConfigEntry('compile_output_path')
130                 ));
131
132                 // Return the prepared instance
133                 return $templateInstance;
134         }
135
136         /**
137          * Getter for current main node
138          *
139          * @return      $currMainNode   Current main node
140          */
141         public final function getCurrMainNode () {
142                 return $this->currMainNode;
143         }
144
145         /**
146          * Getter for main node array
147          *
148          * @return      $mainNodes      Array with valid main node names
149          */
150         public final function getMainNodes () {
151                 return $this->mainNodes;
152         }
153
154         /**
155          * Getter for sub node array
156          *
157          * @return      $subNodes       Array with valid sub node names
158          */
159         public final function getSubNodes () {
160                 return $this->subNodes;
161         }
162
163         /**
164          * Handles the start element of an XML resource
165          *
166          * @param       $resource               XML parser resource (currently ignored)
167          * @param       $element                The element we shall handle
168          * @param       $attributes             All attributes
169          * @return      void
170          * @throws      InvalidXmlNodeException         If an unknown/invalid XML node name was found
171          */
172         public function startElement ($resource, $element, array $attributes) {
173                 // Initial method name which will never be called...
174                 $methodName = 'initImage';
175
176                 // Make the element name lower-case
177                 $element = strtolower($element);
178
179                 // Is the element a main node?
180                 //* DEBUG: */ echo "START: &gt;".$element."&lt;<br />\n";
181                 if (in_array($element, $this->mainNodes)) {
182                         // Okay, main node found!
183                         $methodName = 'setImage' . self::convertToClassName($element);
184                 } elseif (in_array($element, $this->subNodes)) {
185                         // Sub node found
186                         $methodName = 'setImageProperty' . self::convertToClassName($element);
187                 } elseif ($element != 'image') {
188                         // Invalid node name found
189                         throw new InvalidXmlNodeException(array($this, $element, $attributes), XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
190                 }
191
192                 // Call method
193                 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
194                 call_user_func_array(array($this, $methodName), $attributes);
195         }
196
197         /**
198          * Ends the main or sub node by sending out the gathered data
199          *
200          * @param       $resource       An XML resource pointer (currently ignored)
201          * @param       $nodeName       Name of the node we want to finish
202          * @return      void
203          * @throws      XmlNodeMismatchException        If current main node mismatches the closing one
204          */
205         public function finishElement ($resource, $nodeName) {
206                 // Make all lower-case
207                 $nodeName = strtolower($nodeName);
208
209                 // Does this match with current main node?
210                 //* DEBUG: */ echo "END: &gt;".$nodeName."&lt;<br />\n";
211                 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
212                         // Did not match!
213                         throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), XmlParser::EXCEPTION_XML_NODE_MISMATCH);
214                 } elseif (in_array($nodeName, $this->getSubNodes())) {
215                         // Silently ignore sub nodes
216                         return;
217                 }
218
219                 // Construct method name
220                 $methodName = 'finish' . self::convertToClassName($nodeName);
221
222                 // Call the corresponding method
223                 call_user_func_array(array($this->getImageInstance(), $methodName), array());
224         }
225
226         /**
227          * Currently not used
228          *
229          * @param       $resource               XML parser resource (currently ignored)
230          * @param       $characters             Characters to handle
231          * @return      void
232          * @todo        Find something usefull with this!
233          */
234         public function characterHandler ($resource, $characters) {
235                 // Trim all spaces away
236                 $characters = trim($characters);
237
238                 // Is this string empty?
239                 if (empty($characters)) {
240                         // Then skip it silently
241                         return;
242                 } // END - if
243
244                 // Unfinished work!
245                 $this->partialStub('Handling extra characters is not yet supported!');
246         }
247
248         /**
249          * Intializes the image
250          *
251          * @return      void
252          * @todo        Add cache creation here
253          */
254         private function initImage () {
255                 // Unfinished work!
256         }
257
258         /**
259          * Set the image type
260          *
261          * @param       $imageType      Code fragment or direct value holding the image type
262          * @return      void
263          */
264         private function setImageType ($imageType) {
265                 // Set group to general
266                 $this->setVariableGroup('general');
267
268                 // Try to compile it first to get the value from variable stack
269                 $imageType = $this->compileRawCode($imageType);
270
271                 // Now make a class name of it
272                 $className = self::convertToClassName($imageType.'_image');
273
274                 // And try to initiate it
275                 $this->setImageInstance(ObjectFactory::createObjectByName($className, array($this)));
276
277                 // Set current main node to type
278                 $this->currMainNode = 'type';
279         }
280
281         /**
282          * "Setter" for resolution, we first need to collect the resolution from the
283          * sub-nodes. So first, this method will prepare an array for it
284          *
285          * @return      void
286          */
287         private function setImageResolution () {
288                 // Call the image class
289                 $this->getImageInstance()->initResolution();
290
291                 // Current main node is resolution
292                 $this->currMainNode = 'resolution';
293         }
294
295         /**
296          * "Setter" for base information. For more details see above method!
297          *
298          * @return      void
299          * @see         ImageTemplateEngine::setImageResolution
300          */
301         private function setImageBase () {
302                 // Call the image class
303                 $this->getImageInstance()->initBase();
304
305                 // Current main node is resolution
306                 $this->currMainNode = 'base';
307         }
308
309         /**
310          * "Setter" for background-color. For more details see above method!
311          *
312          * @return      void
313          * @see         ImageTemplateEngine::setImageResolution
314          */
315         private function setImageBackgroundColor () {
316                 // Call the image class
317                 $this->getImageInstance()->initBackgroundColor();
318
319                 // Current main node is background-color
320                 $this->currMainNode = 'background-color';
321         }
322
323         /**
324          * "Setter" for foreground-color. For more details see above method!
325          *
326          * @return      void
327          * @see         ImageTemplateEngine::setImageResolution
328          */
329         private function setImageForegroundColor () {
330                 // Call the image class
331                 $this->getImageInstance()->initForegroundColor();
332
333                 // Current main node is foreground-color
334                 $this->currMainNode = 'foreground-color';
335         }
336
337         /**
338          * "Setter" for image-string. For more details see above method!
339          *
340          * @param       $groupable      Whether this image string is groupable
341          * @return      void
342          * @see         ImageTemplateEngine::setImageResolution
343          */
344         private function setImageImageString ($groupable = 'single') {
345                 // Call the image class
346                 $this->getImageInstance()->initImageString($groupable);
347
348                 // Current main node is foreground-color
349                 $this->currMainNode = 'image-string';
350         }
351
352         /**
353          * Setter for image name
354          *
355          * @param       $imageName      Name of the image
356          * @return      void
357          */
358         private function setImagePropertyName ($imageName) {
359                 // Call the image class
360                 $this->getImageInstance()->setImageName($imageName);
361         }
362
363         /**
364          * Setter for image width
365          *
366          * @param       $width  Width of the image or variable
367          * @return      void
368          */
369         private function setImagePropertyWidth ($width) {
370                 // Call the image class
371                 $this->getImageInstance()->setWidth($width);
372         }
373
374         /**
375          * Setter for image height
376          *
377          * @param       $height Height of the image or variable
378          * @return      void
379          */
380         private function setImagePropertyHeight ($height) {
381                 // Call the image class
382                 $this->getImageInstance()->setHeight($height);
383         }
384
385         /**
386          * Setter for image red color
387          *
388          * @param       $red    Red color value
389          * @return      void
390          */
391         private function setImagePropertyRed ($red) {
392                 // Call the image class
393                 $this->getImageInstance()->setRed($red);
394         }
395
396         /**
397          * Setter for image green color
398          *
399          * @param       $green  Green color value
400          * @return      void
401          */
402         private function setImagePropertyGreen ($green) {
403                 // Call the image class
404                 $this->getImageInstance()->setGreen($green);
405         }
406
407         /**
408          * Setter for image blue color
409          *
410          * @param       $blue   Blue color value
411          * @return      void
412          */
413         private function setImagePropertyBlue ($blue) {
414                 // Call the image class
415                 $this->getImageInstance()->setBlue($blue);
416         }
417
418         /**
419          * Setter for string name (identifier)
420          *
421          * @param       $stringName             String name (identifier)
422          * @return      void
423          */
424         private function setImagePropertyStringName ($stringName) {
425                 // Call the image class
426                 $this->getImageInstance()->setStringName($stringName);
427         }
428
429         /**
430          * Setter for font size
431          *
432          * @param       $fontSize       Size of the font
433          * @return      void
434          */
435         private function setImagePropertyFontSize ($fontSize) {
436                 // Call the image class
437                 $this->getImageInstance()->setFontSize($fontSize);
438         }
439
440         /**
441          * Setter for image string
442          *
443          * @param       $imageString    Image string to set
444          * @return      void
445          */
446         private function setImagePropertyText ($imageString) {
447                 // Call the image class
448                 $this->getImageInstance()->setString($imageString);
449         }
450
451         /**
452          * Setter for X coordinate
453          *
454          * @param       $x      X coordinate
455          * @return      void
456          */
457         private function setImagePropertyX ($x) {
458                 // Call the image class
459                 $this->getImageInstance()->setX($x);
460         }
461
462         /**
463          * Setter for Y coordinate
464          *
465          * @param       $y      Y coordinate
466          * @return      void
467          */
468         private function setImagePropertyY ($y) {
469                 // Call the image class
470                 $this->getImageInstance()->setY($y);
471         }
472
473         /**
474          * Getter for image cache file (FQFN)
475          *
476          * @return      $fqfn   Full-qualified file name of the image cache
477          */
478         public function getImageCacheFqfn () {
479                 // Get the FQFN ready
480                 $fqfn = sprintf('%s%s%s/%s.%s',
481                         $this->getConfigInstance()->getConfigEntry('framework_base_path'),
482                         $this->getGenericBasePath(),
483                         'images/_cache',
484                         md5(
485                                 $this->getImageInstance()->getImageName() . ':' . $this->__toString() . ':' . $this->getImageInstance()->__toString()
486                         ),
487                         $this->getImageInstance()->getImageType()
488                 );
489
490                 // Return it
491                 return $fqfn;
492         }
493
494         /**
495          * Outputs the image to the world
496          *
497          * @param       $responseInstance       An instance of a Responseable class
498          * @return      void
499          */
500         public function transferToResponse (Responseable $responseInstance) {
501                 // Set the image instance
502                 $responseInstance->setImageInstance($this->getImageInstance());
503         }
504
505         /**
506          * Load a specified image template into the engine
507          *
508          * @param       $template       The image template we shall load which is
509          *                                              located in 'image' by default
510          * @return      void
511          */
512         public function loadImageTemplate ($template) {
513                 // Set template type
514                 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('image_template_type'));
515
516                 // Load the special template
517                 $this->loadTemplate($template);
518         }
519
520 }