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