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