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