3 namespace Org\Mxchange\CoreFramework\Helper;
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;
14 * A generic helper class with generic methods
16 * @author Roland Haeder <webmaster@shipsimu.org>
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
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.
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.
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/>.
35 abstract class BaseHelper extends BaseFrameworkSystem {
37 * Instance to the class which provides field values
39 private $valueInstance = NULL;
42 * Extra instance to the class which provides field values
44 private $extraInstance = NULL;
47 * Rendered content created by the helper class
49 private $content = '';
57 * Array with sub group
59 private $subGroups = [];
62 * Previously opened group
64 private $previousGroupId = '';
67 * Previously opened sub group
69 private $previousSubGroupId = '';
72 * Total counter for groups and sub groups
74 private $totalCounter = 0;
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;
84 * Protected constructor
86 * @param $className Real name of the class
89 protected function __construct (string $className) {
90 // Call parent constructor
91 parent::__construct($className);
95 * Adds content directly
97 * @param $newContent New content to add
100 protected final function addContent (string $newContent) {
101 $this->content .= trim($newContent) . PHP_EOL;
105 * Add header content to the helper
107 * @param $content Content to to the base
110 protected function addHeaderContent (string $content) {
111 // Add the header content
112 $this->groups['header']['content'] = trim($content);
116 * Add footer content to the helper
118 * @param $content Content to to the base
121 protected function addFooterContent (string $content) {
122 // Add the footer content
123 $this->groups['footer']['content'] = trim($content);
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().
131 * @param $newContent New content to add
134 protected final function addContentToPreviousGroup (string $newContent) {
135 // Check for sub/group
136 if ($this->ifSubGroupOpenedPreviously()) {
138 $subGroupId = $this->getPreviousSubGroupId();
141 $this->subGroups[$subGroupId]['content'] .= $newContent;
142 } elseif ($this->ifGroupOpenedPreviously()) {
144 $groupId = $this->getPreviousGroupId();
147 $this->groups[$groupId]['content'] .= $newContent;
150 $this->addContent($newContent);
157 * @return $content The rendered content by this helper
159 protected final function getContent () {
160 return $this->content;
164 * Public setter for extra instance
166 * @param $extraInstance An extra instance of FrameworkInterface to set
169 public final function setExtraInstance (FrameworkInterface $extraInstance) {
170 $this->extraInstance = $extraInstance;
174 * Assigns a field from the value instance with a template variable
176 * @param $fieldName Name of the field to assign
179 public function assignField (string $fieldName) {
180 // Get the value from value instance
181 $fieldValue = $this->getValueField($fieldName);
183 // Assign it with a template variable
184 $this->getTemplateInstance()->assignVariable('block_' . $fieldName, $fieldValue);
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
191 * @param $fieldName Name of the field to assign
192 * @param $filterMethod Method name to call of the value instance
194 * @todo Rewrite this method using a helper class for filtering data
196 public function assignFieldWithFilter (string $fieldName, string $filterMethod) {
198 $fieldValue = $this->getValueField($fieldName);
199 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.'='.$fieldValue);
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));
204 // Assign it with a template variable
205 $this->getTemplateInstance()->assignVariable('block_' . $fieldName, $filteredValue);
209 * Pre-fetches field default values from the given registry key instance into this class
211 * @param $registryKey Registry key which holds an object with values
212 * @param $extraKey Extra value instance key used if registryKey is null
214 * @throws NullPointerException If recovery of requested value instance failed
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)) {
221 throw new InvalidArgumentException('Parameter "registryKey" is empty');
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!');
233 // Shall we get an extra instance?
234 if (!is_null($extraKey)) {
236 // Get the extra instance.
237 $this->extraInstance = GenericRegistry::getRegistry()->getInstance($extraKey);
238 } catch (NullPointerException $e) {
240 $this->extraInstance = ObjectFactory::createObjectByConfiguredName($extraKey . '_class', array($this->valueInstance));
242 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($extraKey.'='.$this->extraInstance.' - EXTRA!');
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));
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
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
261 * @throws HelperGroupAlreadyCreatedException If the group was already created before
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)) {
268 throw new InvalidArgumentException('Parameter "groupId" is empty');
269 } elseif (isset($this->groups[$groupId])) {
270 // Then throw an exception here
271 throw new HelperGroupAlreadyCreatedException(array($this, $groupId), self::EXCEPTION_GROUP_ALREADY_FOUND);
275 $this->totalCounter++;
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,
287 $this->groups[$groupId]['tag'] = $tag;
289 // Mark this group as previously opened
290 $this->setPreviousGroupId($groupId);
294 * Closes the previously opened group by added given content to it or
295 * throws an exception if no previous group was opened
297 * @param $content Content for previously opened group, or empty to use tag of opener
299 * @throws HelperNoPreviousOpenedGroupException If no previously opened group was found
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();
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);
314 // Get previous group
315 $groupId = $this->getPreviousGroupId();
317 // Is the content empty?
318 if ((empty($content)) && (!empty($this->groups[$groupId]['tag']))) {
319 // Get it from opener
321 "<!-- group %s auto-closed //--></%s>",
323 $this->groups[$groupId]['tag']
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",
332 $this->groups[$groupId]['tag'],
335 $this->groups[$groupId]['opened'] = false;
337 // Mark previous group as closed
338 $this->setPreviousGroupId('');
339 //* DEBUG: */ echo "CLOSE:groupId={$groupId}<br />\n";
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
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
351 * @throws HelperSubGroupAlreadyCreatedException If the sub group was already created before
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)) {
358 throw new InvalidArgumentException('Parameter "subGroupId" is empty');
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);
365 $this->totalCounter++;
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;
373 // Mark this group as previously opened
374 $this->setPreviousSubGroupId($subGroupId);
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
381 * @param $content Content for previously opened sub group, or leave empty to use div/span of openener
383 * @throws HelperNoPreviousOpenedSubGroupException If no previously opened sub group was found
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);
392 // Get previous sub group
393 $subGroupId = $this->getPreviousSubGroupId();
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']);
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
406 // Mark previous sub group as closed
407 $this->setPreviousSubGroupId('');
408 //* DEBUG: */ echo "CLOSE:subGroupId={$subGroupId}<br />\n";
412 * Renders all group and sub group in their order
414 * @return $content Rendered HTML content
416 public function renderContent () {
417 // Initialize content
420 // Is header content there?
421 if (isset($this->groups['header'])) {
423 $content .= $this->groups['header']['content'] . PHP_EOL;
427 $content .= $this->getContent();
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);
443 // Something went wrong
444 $this->debugInstance(__METHOD__ . '(): Something unexpected happened here.');
448 // Is footer content there?
449 if (isset($this->groups['footer'])) {
451 $content .= $this->groups['footer']['content'] . PHP_EOL;
455 //* DEBUG: */ echo "content=<pre>".htmlentities($content)."</pre> (".strlen($content).")<br />\n";
460 * Checks whether the specified group is opened
462 * @param $groupId Id of group to check
463 * @return $isOpened Whether the specified group is open
465 protected function ifGroupIsOpened (string $groupId) {
466 // Is the group open?
467 $isOpened = ((isset($this->groups[$groupId])) && ($this->groups[$groupId]['opened'] === true));
474 * Getter for direct field values
476 * @param $fieldName Name of the field we shall fetch
477 * @return $fieldValue Value from field
478 * @throws NullPointerException Thrown if $valueInstance is null
480 public function getValueField (string $fieldName) {
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);
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!');
501 $this->debugOutput('BASE-HELPER: fieldName=' . $fieldName . ' is not set! - @TODO');
509 * Getter for value instance
511 * @return $valueInstance Instance of the class holding our values
513 public final function getValueInstance () {
514 return $this->valueInstance;
518 * Check whether a group was opened previously
520 * @return $groupOpened Whether any group was opened before
522 protected final function ifGroupOpenedPreviously () {
523 $groupOpened = (!empty($this->previousGroupId));
528 * Check whether a group was opened previously
530 * @return $subGroupOpened Whether any group was opened before
532 protected final function ifSubGroupOpenedPreviously () {
533 $subGroupOpened = (!empty($this->previousSubGroupId));
534 return $subGroupOpened;
538 * Getter for previous group id
540 * @return $previousGroupId Id of previously opened group
542 protected final function getPreviousGroupId () {
543 return $this->previousGroupId;
547 * Setter for previous group id
549 * @param $previousGroupId Id of previously opened group
552 protected final function setPreviousGroupId (string $previousGroupId) {
553 $this->previousGroupId = $previousGroupId;
557 * Getter for previous sub group id
559 * @return $previousSubGroupId Id of previously opened sub group
561 protected final function getPreviousSubGroupId () {
562 return $this->previousSubGroupId;
566 * Setter for previous sub group id
568 * @param $previousSubGroupId Id of previously opened sub group
571 protected final function setPreviousSubGroupId (string $previousSubGroupId) {
572 $this->previousSubGroupId = $previousSubGroupId;