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