Misc fixes:
[core.git] / inc / classes / main / helper / class_BaseHelper.php
1 <?php
2 /**
3  * A generic helper class with generic methods
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 Core Developer Team
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 BaseHelper extends BaseFrameworkSystem {
25         /**
26          * Instance to the class which provides field values
27          */
28         private $valueInstance = null;
29
30         /**
31          * Extra instance to the class which provides field values
32          */
33         private $extraInstance = null;
34
35         /**
36          * Rendered content created by the helper class
37          */
38         private $content = '';
39
40         /**
41          * Array with groups
42          */
43         private $groups = array();
44
45         /**
46          * Array with sub group
47          */
48         private $subGroups = array();
49
50         /**
51          * Previously opened group
52          */
53         private $previousGroupId = '';
54
55         /**
56          * Previously opened sub group
57          */
58         private $previousSubGroupId = '';
59
60         /**
61          * Total counter for groups and sub groups
62          */
63         private $totalCounter = 0;
64
65         // Exception constants
66         const EXCEPTION_XML_PARSER_ERROR             = 0x1e0;
67         const EXCEPTION_XML_NODE_UNKNOWN             = 0x1e1;
68         const EXCEPTION_XML_NODE_MISMATCH            = 0x1e2;
69         const EXCEPTION_GROUP_NOT_OPENED             = 0x1e3;
70         const EXCEPTION_GROUP_ALREADY_FOUND          = 0x1e4;
71         const EXCEPTION_SUB_GROUP_ALREADY_FOUND      = 0x1e5;
72         const EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED = 0x1e6;
73         const EXCEPTION_NO_PREVIOUS_GROUP_OPENED     = 0x1e7;
74
75         /**
76          * Protected constructor
77          *
78          * @param       $className      Real name of the class
79          * @return      void
80          */
81         protected function __construct ($className) {
82                 // Call parent constructor
83                 parent::__construct($className);
84         }
85
86         /**
87          * Adds content directly
88          *
89          * @param       $newContent             New content to add
90          * @return      void
91          */
92         protected final function addContent ($newContent) {
93                 $this->content .= (string) trim($newContent) . "\n";
94         }
95
96         /**
97          * Add header content to the helper
98          *
99          * @param       $content        Content to to the base
100          * @return      void
101          */
102         protected function addHeaderContent ($content) {
103                 // Add the header content
104                 $this->groups['header']['content'] = (string) trim($content);
105         }
106
107         /**
108          * Add footer content to the helper
109          *
110          * @param       $content        Content to to the base
111          * @return      void
112          */
113         protected function addFooterContent ($content) {
114                 // Add the footer content
115                 $this->groups['footer']['content'] = (string) trim($content);
116         }
117
118         /**
119          * Adds content to the previously opened group or sub group. If a sub group
120          * was found it will be taken. If no group/sub group is opened at the moment
121          * the code will be passed to addContent().
122          *
123          * @param       $newContent             New content to add
124          * @return      void
125          */
126         protected final function addContentToPreviousGroup ($newContent) {
127                 // Check for sub/group
128                 if ($this->ifSubGroupOpenedPreviously()) {
129                         // Get sub group id
130                         $subGroupId = $this->getPreviousSubGroupId();
131
132                         // Add the content
133                         $this->subGroups[$subGroupId]['content'] .= $newContent;
134                 } elseif ($this->ifGroupOpenedPreviously()) {
135                         // Get group id
136                         $groupId = $this->getPreviousGroupId();
137
138                         // Add the content
139                         $this->groups[$groupId]['content'] .= $newContent;
140                 } else {
141                         // Add it directly
142                         $this->addContent($newContent);
143                 }
144         }
145
146         /**
147          * Getter for content
148          *
149          * @return      $content        The rendered content by this helper
150          */
151         protected final function getContent () {
152                 return $this->content;
153         }
154
155         /**
156          *  Assigns a field from the value instance with a template variable
157          *
158          * @param       $fieldName      Name of the field to assign
159          * @return      void
160          */
161         public function assignField ($fieldName) {
162                 // Get the value from value instance
163                 $fieldValue = $this->getValueField($fieldName);
164
165                 // Assign it with a template variable
166                 $this->getTemplateInstance()->assignVariable('block_' . $fieldName, $fieldValue);
167         }
168
169         /**
170          * Assigns a field from the value instance with a template variable but
171          * parses its content through a given filter method of the value instance
172          *
173          * @param       $fieldName              Name of the field to assign
174          * @param       $filterMethod   Method name to call of the value instance
175          * @return      void
176          * @todo        Rewrite this method using a helper class for filtering data
177          */
178         public function assignFieldWithFilter ($fieldName, $filterMethod) {
179                 // Get the value
180                 $fieldValue = $this->getValueField($fieldName);
181                 //* DEBUG: */ $this->debugOutput($fieldName.'='.$fieldValue);
182
183                 // Now filter it through the value through the filter method
184                 $filteredValue = call_user_func_array(array($this, 'doFilter' . $this->convertToClassName($filterMethod)), array($fieldValue));
185
186                 // Assign it with a template variable
187                 $this->getTemplateInstance()->assignVariable('block_' . $fieldName, $filteredValue);
188         }
189
190         /**
191          * Pre-fetches field default values from the given registry key instance into this class
192          *
193          * @param       $registryKey    Registry key which holds an object with values
194          * @param       $extraKey               Extra value instance key used if registryKey is null
195          * @return      void
196          * @throws      NullPointerException    If recovery of requested value instance failed
197          */
198         public function prefetchValueInstance ($registryKey, $extraKey = null) {
199                 //* DEBUG: */ $this->debugOutput('O:'.$registryKey.'/'.$extraKey);
200                 try {
201                         // Get the required instance
202                         $this->valueInstance = Registry::getRegistry()->getInstance($registryKey);
203                 } catch (NullPointerException $e) {
204                         // Not set in registry
205                         // @TODO Try to log it here
206                         //* DEBUG: */ $this->debugOutput($registryKey.'=NULL!');
207                 }
208
209                 // Shall we get an extra instance?
210                 if (!is_null($extraKey)) {
211                         try {
212                                 // Get the extra instance.
213                                 $this->extraInstance = Registry::getRegistry()->getInstance($extraKey);
214                         } catch (NullPointerException $e) {
215                                 // Try to create it
216                                 $this->extraInstance = ObjectFactory::createObjectByConfiguredName($extraKey . '_class', array($this->valueInstance));
217                         }
218                         //* DEBUG: */ $this->debugOutput($extraKey.'='.$this->extraInstance.' - EXTRA!');
219                 } // END - if
220
221                 // Is the value instance valid?
222                 if (is_null($this->valueInstance)) {
223                         try {
224                                 // Get the requested instance
225                                 $this->valueInstance = ObjectFactory::createObjectByConfiguredName($registryKey . '_class', array($this->extraInstance));
226                         } catch (FrameworkException $e) {
227                                 // Okay, nothing found so throw a null pointer exception here
228                                 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
229                         }
230                 } // END - if
231         }
232
233         /**
234          * Opens a helper group with given group id and content or throws an
235          * exception if that group is already found regardless if it is open or
236          * closed.
237          *
238          * @param       $groupId        Group id to open
239          * @param       $content        Initial content to add to the group
240          * @param       $tag            HTML tag used to open this group
241          * @return      void
242          * @throws      HelperGroupAlreadyCreatedException      If the group was already created before
243          */
244         protected function openGroupByIdContent ($groupId, $content, $tag) {
245                 //* DEBUG: */ echo "OPEN:groupId={$groupId},content=<pre>".htmlentities($content)."</pre>\n";
246                 // Is the group already there?
247                 if (isset($this->groups[$groupId])) {
248                         // Then throw an exception here
249                         throw new HelperGroupAlreadyCreatedException(array($this, $groupId), self::EXCEPTION_GROUP_ALREADY_FOUND);
250                 } // END - if
251
252                 // Count one up
253                 $this->totalCounter++;
254
255                 // Add the group to the stack
256                 $this->groups[$this->totalCounter] = $groupId;
257                 $this->groups[$groupId]['opened']  = true;
258                 $this->groups[$groupId]['content'] = sprintf(
259                         "<!-- group %s opened (length: %s, tag: %s) //-->%s\n",
260                         $groupId,
261                         strlen($content),
262                         $tag,
263                         $content
264                 );
265                 $this->groups[$groupId]['tag'] = $tag;
266
267                 // Mark this group as previously opened
268                 $this->setPreviousGroupId($groupId);
269         }
270
271         /**
272          * Closes the previously opened group by added given content to it or
273          * throws an exception if no previous group was opened
274          *
275          * @param       $content        Content for previously opened group, or empty to use tag of opener
276          * @return      void
277          * @throws      HelperNoPreviousOpenedGroupException    If no previously opened group was found
278          */
279         public function closePreviousGroupByContent ($content = '') {
280                 // Check if any sub group was opened before
281                 if ($this->ifSubGroupOpenedPreviously()) {
282                         // Close it automatically
283                         $this->closePreviousSubGroupByContent();
284                 } // END - if
285
286                 // Check if any group was opened before
287                 if ($this->ifGroupOpenedPreviously() === false) {
288                         // Then throw an exception
289                         throw new HelperNoPreviousOpenedGroupException(array($this, $content), self::EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED);
290                 } // END - if
291
292                 // Get previous group
293                 $groupId = $this->getPreviousGroupId();
294
295                 // Is the content empty?
296                 if ((empty($content)) && (!empty($this->groups[$groupId]['tag']))) {
297                         // Get it from opener
298                         $content = sprintf(
299                                 "<!-- group %s auto-closed //--></%s>",
300                                 $groupId,
301                                 $this->groups[$groupId]['tag']
302                         );
303                 } // END - if
304
305                 // Add content to it and mark it as closed
306                 $this->groups[$groupId]['content'] .= sprintf(
307                         "<!-- group %s closed (length: %s, tag: %s) //-->%s\n",
308                         $groupId,
309                         strlen($content),
310                         $this->groups[$groupId]['tag'],
311                         $content
312                 );
313                 $this->groups[$groupId]['opened'] = false;
314
315                 // Mark previous group as closed
316                 $this->setPreviousGroupId('');
317                 //* DEBUG: */ echo "CLOSE:groupId={$groupId}<br />\n";
318         }
319
320         /**
321          * Opens a helper sub group with given group id and content or throws an
322          * exception if that sub group is already found regardless if it is open or
323          * closed.
324          *
325          * @param       $subGroupId             Sub group id to open
326          * @param       $content                Initial content to add to the sub group
327          * @param       $tag                    HTML tag used to open this group
328          * @return      void
329          * @throws      HelperSubGroupAlreadyCreatedException   If the sub group was already created before
330          */
331         protected function openSubGroupByIdContent ($subGroupId, $content, $tag) {
332                 //* DEBUG: */ echo "OPEN:subGroupId={$subGroupId},content=".htmlentities($content)."<br />\n";
333                 // Is the group already there?
334                 if (isset($this->subGroups[$subGroupId])) {
335                         // Then throw an exception here
336                         throw new HelperSubGroupAlreadyCreatedException(array($this, $subGroupId), self::EXCEPTION_SUB_GROUP_ALREADY_FOUND);
337                 } // END - if
338
339                 // Count one up
340                 $this->totalCounter++;
341
342                 // Add the group to the stack
343                 $this->subGroups[$this->totalCounter] = $subGroupId;
344                 $this->subGroups[$subGroupId]['opened']  = true;
345                 $this->subGroups[$subGroupId]['content'] = sprintf("<!-- sub-group %s opened (length: %s, tag: %s) //-->%s\n", $subGroupId, strlen($content), $tag, $content);
346                 $this->subGroups[$subGroupId]['tag'] = $tag;
347
348                 // Mark this group as previously opened
349                 $this->setPreviousSubGroupId($subGroupId);
350         }
351
352         /**
353          * Closes the previously opened sub group by added given content to it or
354          * throws an exception if no previous sub group was opened
355          *
356          * @param       $content        Content for previously opened sub group, or leave empty to use div/span of openener
357          * @return      void
358          * @throws      HelperNoPreviousOpenedSubGroupException If no previously opened sub group was found
359          */
360         public function closePreviousSubGroupByContent ($content = '') {
361                 // Check if any sub group was opened before
362                 if ($this->ifSubGroupOpenedPreviously() === false) {
363                         // Then throw an exception
364                         throw new HelperNoPreviousOpenedSubGroupException(array($this, $content), self::EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED);
365                 } // END - if
366
367                 // Get previous sub group
368                 $subGroupId = $this->getPreviousSubGroupId();
369
370                 // Is the content empty?
371                 if ((empty($content)) && (!empty($this->subGroups[$subGroupId]['tag']))) {
372                         // Get it from opener
373                         $content = sprintf("<!-- sub-group %s auto-closed //--></%s>", $subGroupId, $this->subGroups[$subGroupId]['tag']);
374                 } // END - if
375
376                 // Add content to it and mark it as closed
377                 $this->subGroups[$subGroupId]['content'] .= sprintf("<!-- sub-group %s closed (length: %s, tag: %s) //-->%s\n", $subGroupId, strlen($content), $this->subGroups[$subGroupId]['tag'], $content);
378                 $this->subGroups[$subGroupId]['opened'] = false;
379
380                 // Mark previous sub group as closed
381                 $this->setPreviousSubGroupId('');
382                 //* DEBUG: */ echo "CLOSE:subGroupId={$subGroupId}<br />\n";
383         }
384
385         /**
386          * Renders all group and sub group in their order
387          *
388          * @return      $content        Rendered HTML content
389          */
390         public function renderContent () {
391                 // Initialize content
392                 $content = '';
393
394                 // Is header content there?
395                 if (isset($this->groups['header'])) {
396                         // Then add it
397                         $content .= $this->groups['header']['content'] . "\n";
398                 } // END - if
399
400                 // Initiate content
401                 $content .= $this->getContent();
402
403                 // Now "walk" through all groups and sub-groups
404                 for ($idx = 1; $idx <= $this->totalCounter; $idx++) {
405                         // Is this a group and is it closed?
406                         if ((isset($this->groups[$idx])) && ($this->groups[$this->groups[$idx]]['opened'] === false)) {
407                                 // Then add it's content
408                                 $groupContent = trim($this->groups[$this->groups[$idx]]['content']);
409                                 //* DEBUG: */ echo "group={$this->groups[$idx]},content=<pre>".htmlentities($groupContent)."</pre><br />\n";
410                                 $content .= $groupContent;
411                         } elseif ((isset($this->subGroups[$idx])) && ($this->subGroups[$this->subGroups[$idx]]['opened'] === false)) {
412                                 // Then add it's content
413                                 $subGroupContent = $this->subGroups[$this->subGroups[$idx]]['content'];
414                                 //* DEBUG: */ echo "subgroup={$this->subGroups[$idx]},content=<pre>".htmlentities($subGroupContent)."</pre><br />\n";
415                                 $content .= trim($subGroupContent);
416                         } else {
417                                 // Something went wrong
418                                 $this->debugInstance(__METHOD__."(): Something unexpected happened here.");
419                         }
420                 } // END - for
421
422                 // Is footer content there?
423                 if (isset($this->groups['footer'])) {
424                         // Then add it
425                         $content .= $this->groups['footer']['content'] . "\n";
426                 } // END - if
427
428                 // Return it
429                 //* DEBUG: */ echo "content=<pre>".htmlentities($content)."</pre> (".strlen($content).")<br />\n";
430                 return $content;
431         }
432
433         /**
434          * Checks wether the specified group is opened
435          *
436          * @param       $groupId        Id of group to check
437          * @return      $isOpened       Wether the specified group is open
438          */
439         protected function ifGroupIsOpened ($groupId) {
440                 // Is the group open?
441                 $isOpened = ((isset($this->groups[$groupId])) && ($this->groups[$groupId]['opened'] === true));
442
443                 // Return status
444                 return $isOpened;
445         }
446
447         /**
448          * Getter for direct field values
449          *
450          * @param       $fieldName              Name of the field we shall fetch
451          * @return      $fieldValue             Value from field
452          * @throws      NullPointerException    Thrown if $valueInstance is null
453          */
454         public function getValueField ($fieldName) {
455                 // The $valueInstance attribute should not be null!
456                 if (is_null($this->getValueInstance())) {
457                         // Throws an exception here
458                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
459                 } // END - if
460
461                 // Get the field value
462                 $fieldValue = $this->getValueInstance()->getField($fieldName);
463                 //* DEBUG: */ $this->debugOutput($fieldName.'[]='.gettype($fieldValue).'('.strlen($fieldValue).')');
464
465                 // Is it null?
466                 if ((is_null($fieldValue)) && (!is_null($this->extraInstance))) {
467                         // So try the extra instance
468                         $fieldValue = $this->extraInstance->getField($fieldName);
469                 } // END - if
470
471                 // Return it
472                 return $fieldValue;
473         }
474
475         /**
476          * Getter for value instance
477          *
478          * @return      $valueInstance  Instance of the class holding our values
479          */
480         public final function getValueInstance () {
481                 return $this->valueInstance;
482         }
483
484         /**
485          * Check wether a group was opened previously
486          *
487          * @return      $groupOpened    Wether any group was opened before
488          */
489         protected final function ifGroupOpenedPreviously () {
490                 $groupOpened = (!empty($this->previousGroupId));
491                 return $groupOpened;
492         }
493
494         /**
495          * Check wether a group was opened previously
496          *
497          * @return      $subGroupOpened         Wether any group was opened before
498          */
499         protected final function ifSubGroupOpenedPreviously () {
500                 $subGroupOpened = (!empty($this->previousSubGroupId));
501                 return $subGroupOpened;
502         }
503
504         /**
505          * Getter for previous group id
506          *
507          * @return      $previousGroupId        Id of previously opened group
508          */
509         protected final function getPreviousGroupId () {
510                 return $this->previousGroupId;
511         }
512
513         /**
514          * Setter for previous group id
515          *
516          * @param       $previousGroupId        Id of previously opened group
517          * @return      void
518          */
519         protected final function setPreviousGroupId ($previousGroupId) {
520                 $this->previousGroupId = (string) $previousGroupId;
521         }
522
523         /**
524          * Getter for previous sub group id
525          *
526          * @return      $previousSubGroupId             Id of previously opened sub group
527          */
528         protected final function getPreviousSubGroupId () {
529                 return $this->previousSubGroupId;
530         }
531
532         /**
533          * Setter for previous sub group id
534          *
535          * @param       $previousSubGroupId             Id of previously opened sub group
536          * @return      void
537          */
538         protected final function setPreviousSubGroupId ($previousSubGroupId) {
539                 $this->previousSubGroupId = (string) $previousSubGroupId;
540         }
541 }
542
543 // [EOF]
544 ?>