]> 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\Object\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\Strings\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 - 2022 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 (string $newContent) {
101                 $this->content .= 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 (string $content) {
111                 // Add the header content
112                 $this->groups['header']['content'] = 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 (string $content) {
122                 // Add the footer content
123                 $this->groups['footer']['content'] = 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 (string $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 (string $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                 // Validate parameter
218                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('O:'.$registryKey.'/'.$extraKey);
219                 if (empty($registryKey)) {
220                         // Throw IAE
221                         throw new InvalidArgumentException('Parameter "registryKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
222                 }
223
224                 try {
225                         // Get the required instance
226                         $this->valueInstance = GenericRegistry::getRegistry()->getInstance($registryKey);
227                 } catch (NullPointerException $e) {
228                         // Not set in registry
229                         // @TODO Try to log it here
230                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($registryKey.'=NULL!');
231                 }
232
233                 // Shall we get an extra instance?
234                 if (!is_null($extraKey)) {
235                         try {
236                                 // Get the extra instance.
237                                 $this->extraInstance = GenericRegistry::getRegistry()->getInstance($extraKey);
238                         } catch (NullPointerException $e) {
239                                 // Try to create it
240                                 $this->extraInstance = ObjectFactory::createObjectByConfiguredName($extraKey . '_class', array($this->valueInstance));
241                         }
242                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($extraKey.'='.$this->extraInstance.' - EXTRA!');
243                 }
244
245                 // Is the value instance valid?
246                 if (is_null($this->valueInstance)) {
247                         // Get the requested instance
248                         $this->valueInstance = ObjectFactory::createObjectByConfiguredName($registryKey . '_class', array($this->extraInstance));
249                 }
250         }
251
252         /**
253          * Opens a helper group with given group id and content or throws an
254          * exception if that group is already found regardless if it is open or
255          * closed.
256          *
257          * @param       $groupId        Group id to open
258          * @param       $content        Initial content to add to the group
259          * @param       $tag            HTML tag used to open this group
260          * @return      void
261          * @throws      HelperGroupAlreadyCreatedException      If the group was already created before
262          */
263         protected function openGroupByIdContent (string $groupId, string $content, string $tag) {
264                 // Is the group already there?
265                 //* DEBUG: */ echo "OPEN:groupId={$groupId},content=<pre>".htmlentities($content)."</pre>\n";
266                 if (empty($groupId)) {
267                         // Throw IAE
268                         throw new InvalidArgumentException('Parameter "groupId" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
269                 } elseif (isset($this->groups[$groupId])) {
270                         // Then throw an exception here
271                         throw new HelperGroupAlreadyCreatedException(array($this, $groupId), self::EXCEPTION_GROUP_ALREADY_FOUND);
272                 }
273
274                 // Count one up
275                 $this->totalCounter++;
276
277                 // Add the group to the stack
278                 $this->groups[$this->totalCounter] = $groupId;
279                 $this->groups[$groupId]['opened']  = true;
280                 $this->groups[$groupId]['content'] = sprintf(
281                         '<!-- group %s opened (length: %s, tag: %s) //-->%s' . PHP_EOL,
282                         $groupId,
283                         strlen($content),
284                         $tag,
285                         $content
286                 );
287                 $this->groups[$groupId]['tag'] = $tag;
288
289                 // Mark this group as previously opened
290                 $this->setPreviousGroupId($groupId);
291         }
292
293         /**
294          * Closes the previously opened group by added given content to it or
295          * throws an exception if no previous group was opened
296          *
297          * @param       $content        Content for previously opened group, or empty to use tag of opener
298          * @return      void
299          * @throws      HelperNoPreviousOpenedGroupException    If no previously opened group was found
300          */
301         public function closePreviousGroupByContent (string $content = '') {
302                 // Check if any sub group was opened before
303                 if ($this->ifSubGroupOpenedPreviously()) {
304                         // Close it automatically
305                         $this->closePreviousSubGroupByContent();
306                 }
307
308                 // Check if any group was opened before
309                 if ($this->ifGroupOpenedPreviously() === false) {
310                         // Then throw an exception
311                         throw new HelperNoPreviousOpenedGroupException(array($this, $content), self::EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED);
312                 }
313
314                 // Get previous group
315                 $groupId = $this->getPreviousGroupId();
316
317                 // Is the content empty?
318                 if ((empty($content)) && (!empty($this->groups[$groupId]['tag']))) {
319                         // Get it from opener
320                         $content = sprintf(
321                                 "<!-- group %s auto-closed //--></%s>",
322                                 $groupId,
323                                 $this->groups[$groupId]['tag']
324                         );
325                 }
326
327                 // Add content to it and mark it as closed
328                 $this->groups[$groupId]['content'] .= sprintf(
329                         "<!-- group %s closed (length: %s, tag: %s) //-->%s\n",
330                         $groupId,
331                         strlen($content),
332                         $this->groups[$groupId]['tag'],
333                         $content
334                 );
335                 $this->groups[$groupId]['opened'] = false;
336
337                 // Mark previous group as closed
338                 $this->setPreviousGroupId('');
339                 //* DEBUG: */ echo "CLOSE:groupId={$groupId}<br />\n";
340         }
341
342         /**
343          * Opens a helper sub group with given group id and content or throws an
344          * exception if that sub group is already found regardless if it is open or
345          * closed.
346          *
347          * @param       $subGroupId             Sub group id to open
348          * @param       $content                Initial content to add to the sub group
349          * @param       $tag                    HTML tag used to open this group
350          * @return      void
351          * @throws      HelperSubGroupAlreadyCreatedException   If the sub group was already created before
352          */
353         protected function openSubGroupByIdContent (string $subGroupId, string $content, string $tag) {
354                 //* DEBUG: */ echo "OPEN:subGroupId={$subGroupId},content=".htmlentities($content)."<br />\n";
355                 // Is the group already there?
356                 if (empty($subGroupId)) {
357                         // Throw IAE
358                         throw new InvalidArgumentException('Parameter "subGroupId" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
359                 } elseif (isset($this->subGroups[$subGroupId])) {
360                         // Then throw an exception here
361                         throw new HelperSubGroupAlreadyCreatedException(array($this, $subGroupId), self::EXCEPTION_SUB_GROUP_ALREADY_FOUND);
362                 }
363
364                 // Count one up
365                 $this->totalCounter++;
366
367                 // Add the group to the stack
368                 $this->subGroups[$this->totalCounter] = $subGroupId;
369                 $this->subGroups[$subGroupId]['opened']  = true;
370                 $this->subGroups[$subGroupId]['content'] = sprintf("<!-- sub-group %s opened (length: %s, tag: %s) //-->%s\n", $subGroupId, strlen($content), $tag, $content);
371                 $this->subGroups[$subGroupId]['tag'] = $tag;
372
373                 // Mark this group as previously opened
374                 $this->setPreviousSubGroupId($subGroupId);
375         }
376
377         /**
378          * Closes the previously opened sub group by added given content to it or
379          * throws an exception if no previous sub group was opened
380          *
381          * @param       $content        Content for previously opened sub group, or leave empty to use div/span of openener
382          * @return      void
383          * @throws      HelperNoPreviousOpenedSubGroupException If no previously opened sub group was found
384          */
385         public function closePreviousSubGroupByContent (string $content = '') {
386                 // Check if any sub group was opened before
387                 if ($this->ifSubGroupOpenedPreviously() === false) {
388                         // Then throw an exception
389                         throw new HelperNoPreviousOpenedSubGroupException(array($this, $content), self::EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED);
390                 }
391
392                 // Get previous sub group
393                 $subGroupId = $this->getPreviousSubGroupId();
394
395                 // Is the content empty?
396                 if ((empty($content)) && (!empty($this->subGroups[$subGroupId]['tag']))) {
397                         // Get it from opener
398                         $content = sprintf('<!-- sub-group %s auto-closed //--></%s>', $subGroupId, $this->subGroups[$subGroupId]['tag']);
399                 }
400
401                 // Add content to it and mark it as closed
402                 $this->subGroups[$subGroupId]['content'] .= sprintf('<!-- sub-group %s closed (length: %s, tag: %s) //-->%s' . PHP_EOL, $subGroupId, strlen($content), $this->subGroups[$subGroupId]['tag'], $content);
403                 $this->subGroups[$subGroupId]['opened'] = false
404                 ;
405
406                 // Mark previous sub group as closed
407                 $this->setPreviousSubGroupId('');
408                 //* DEBUG: */ echo "CLOSE:subGroupId={$subGroupId}<br />\n";
409         }
410
411         /**
412          * Renders all group and sub group in their order
413          *
414          * @return      $content        Rendered HTML content
415          */
416         public function renderContent () {
417                 // Initialize content
418                 $content = '';
419
420                 // Is header content there?
421                 if (isset($this->groups['header'])) {
422                         // Then add it
423                         $content .= $this->groups['header']['content'] . PHP_EOL;
424                 }
425
426                 // Initiate content
427                 $content .= $this->getContent();
428
429                 // Now "walk" through all groups and sub-groups
430                 for ($idx = 1; $idx <= $this->totalCounter; $idx++) {
431                         // Is this a sub/group and is it closed?
432                         if ((isset($this->groups[$idx])) && ($this->groups[$this->groups[$idx]]['opened'] === false)) {
433                                 // Then add it's content
434                                 $groupContent = trim($this->groups[$this->groups[$idx]]['content']);
435                                 //* DEBUG: */ echo "group={$this->groups[$idx]},content=<pre>".htmlentities($groupContent)."</pre><br />\n";
436                                 $content .= $groupContent;
437                         } elseif ((isset($this->subGroups[$idx])) && ($this->subGroups[$this->subGroups[$idx]]['opened'] === false)) {
438                                 // Then add it's content
439                                 $subGroupContent = $this->subGroups[$this->subGroups[$idx]]['content'];
440                                 //* DEBUG: */ echo "subgroup={$this->subGroups[$idx]},content=<pre>".htmlentities($subGroupContent)."</pre><br />\n";
441                                 $content .= trim($subGroupContent);
442                         } else {
443                                 // Something went wrong
444                                 $this->debugInstance(__METHOD__ . '(): Something unexpected happened here.');
445                         }
446                 }
447
448                 // Is footer content there?
449                 if (isset($this->groups['footer'])) {
450                         // Then add it
451                         $content .= $this->groups['footer']['content'] . PHP_EOL;
452                 }
453
454                 // Return it
455                 //* DEBUG: */ echo "content=<pre>".htmlentities($content)."</pre> (".strlen($content).")<br />\n";
456                 return $content;
457         }
458
459         /**
460          * Checks whether the specified group is opened
461          *
462          * @param       $groupId        Id of group to check
463          * @return      $isOpened       Whether the specified group is open
464          */
465         protected function ifGroupIsOpened (string $groupId) {
466                 // Is the group open?
467                 $isOpened = ((isset($this->groups[$groupId])) && ($this->groups[$groupId]['opened'] === true));
468
469                 // Return status
470                 return $isOpened;
471         }
472
473         /**
474          * Getter for direct field values
475          *
476          * @param       $fieldName              Name of the field we shall fetch
477          * @return      $fieldValue             Value from field
478          * @throws      NullPointerException    Thrown if $valueInstance is null
479          */
480         public function getValueField (string $fieldName) {
481                 // Init value
482                 $fieldValue = NULL;
483
484                 // The $valueInstance attribute should not be null!
485                 if (is_null($this->getValueInstance())) {
486                         // Throws an exception here
487                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
488                 }
489
490                 // Is the field set?
491                 if ($this->getValueInstance()->isFieldSet($fieldName)) {
492                         // Get the field value
493                         $fieldValue = $this->getValueInstance()->getField($fieldName);
494                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.'[]='.gettype($fieldValue).'('.strlen($fieldValue).') - Value instance!');
495                 } elseif ((!is_null($this->extraInstance)) && ($this->extraInstance->isFieldSet($fieldName))) {
496                         // So try the extra instance
497                         $fieldValue = $this->extraInstance->getField($fieldName);
498                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.'[]='.gettype($fieldValue).'('.strlen($fieldValue).') - Extra instance!');
499                 } else {
500                         // Field is not set
501                         $this->debugOutput('BASE-HELPER: fieldName=' . $fieldName . ' is not set! - @TODO');
502                 }
503
504                 // Return it
505                 return $fieldValue;
506         }
507
508         /**
509          * Getter for value instance
510          *
511          * @return      $valueInstance  Instance of the class holding our values
512          */
513         public final function getValueInstance () {
514                 return $this->valueInstance;
515         }
516
517         /**
518          * Check whether a group was opened previously
519          *
520          * @return      $groupOpened    Whether any group was opened before
521          */
522         protected final function ifGroupOpenedPreviously () {
523                 $groupOpened = (!empty($this->previousGroupId));
524                 return $groupOpened;
525         }
526
527         /**
528          * Check whether a group was opened previously
529          *
530          * @return      $subGroupOpened         Whether any group was opened before
531          */
532         protected final function ifSubGroupOpenedPreviously () {
533                 $subGroupOpened = (!empty($this->previousSubGroupId));
534                 return $subGroupOpened;
535         }
536
537         /**
538          * Getter for previous group id
539          *
540          * @return      $previousGroupId        Id of previously opened group
541          */
542         protected final function getPreviousGroupId () {
543                 return $this->previousGroupId;
544         }
545
546         /**
547          * Setter for previous group id
548          *
549          * @param       $previousGroupId        Id of previously opened group
550          * @return      void
551          */
552         protected final function setPreviousGroupId (string $previousGroupId) {
553                 $this->previousGroupId = $previousGroupId;
554         }
555
556         /**
557          * Getter for previous sub group id
558          *
559          * @return      $previousSubGroupId             Id of previously opened sub group
560          */
561         protected final function getPreviousSubGroupId () {
562                 return $this->previousSubGroupId;
563         }
564
565         /**
566          * Setter for previous sub group id
567          *
568          * @param       $previousSubGroupId             Id of previously opened sub group
569          * @return      void
570          */
571         protected final function setPreviousSubGroupId (string $previousSubGroupId) {
572                 $this->previousSubGroupId = $previousSubGroupId;
573         }
574
575 }