3 namespace Org\Mxchange\CoreFramework\Helper;
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;
14 * A generic helper class with generic methods
16 * @author Roland Haeder <webmaster@shipsimu.org>
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
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 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('O:'.$registryKey.'/'.$extraKey);
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!');
227 // Shall we get an extra instance?
228 if (!is_null($extraKey)) {
230 // Get the extra instance.
231 $this->extraInstance = GenericRegistry::getRegistry()->getInstance($extraKey);
232 } catch (NullPointerException $e) {
234 $this->extraInstance = ObjectFactory::createObjectByConfiguredName($extraKey . '_class', array($this->valueInstance));
236 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($extraKey.'='.$this->extraInstance.' - EXTRA!');
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));
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
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
255 * @throws HelperGroupAlreadyCreatedException If the group was already created before
257 protected function openGroupByIdContent (string $groupId, string $content, string $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);
266 $this->totalCounter++;
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,
278 $this->groups[$groupId]['tag'] = $tag;
280 // Mark this group as previously opened
281 $this->setPreviousGroupId($groupId);
285 * Closes the previously opened group by added given content to it or
286 * throws an exception if no previous group was opened
288 * @param $content Content for previously opened group, or empty to use tag of opener
290 * @throws HelperNoPreviousOpenedGroupException If no previously opened group was found
292 public function closePreviousGroupByContent (string $content = '') {
293 // Check if any sub group was opened before
294 if ($this->ifSubGroupOpenedPreviously()) {
295 // Close it automatically
296 $this->closePreviousSubGroupByContent();
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);
305 // Get previous group
306 $groupId = $this->getPreviousGroupId();
308 // Is the content empty?
309 if ((empty($content)) && (!empty($this->groups[$groupId]['tag']))) {
310 // Get it from opener
312 "<!-- group %s auto-closed //--></%s>",
314 $this->groups[$groupId]['tag']
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",
323 $this->groups[$groupId]['tag'],
326 $this->groups[$groupId]['opened'] = false;
328 // Mark previous group as closed
329 $this->setPreviousGroupId('');
330 //* DEBUG: */ echo "CLOSE:groupId={$groupId}<br />\n";
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
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
342 * @throws HelperSubGroupAlreadyCreatedException If the sub group was already created before
344 protected function openSubGroupByIdContent (string $subGroupId, string $content, string $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);
353 $this->totalCounter++;
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;
361 // Mark this group as previously opened
362 $this->setPreviousSubGroupId($subGroupId);
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
369 * @param $content Content for previously opened sub group, or leave empty to use div/span of openener
371 * @throws HelperNoPreviousOpenedSubGroupException If no previously opened sub group was found
373 public function closePreviousSubGroupByContent (string $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);
380 // Get previous sub group
381 $subGroupId = $this->getPreviousSubGroupId();
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']);
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
394 // Mark previous sub group as closed
395 $this->setPreviousSubGroupId('');
396 //* DEBUG: */ echo "CLOSE:subGroupId={$subGroupId}<br />\n";
400 * Renders all group and sub group in their order
402 * @return $content Rendered HTML content
404 public function renderContent () {
405 // Initialize content
408 // Is header content there?
409 if (isset($this->groups['header'])) {
411 $content .= $this->groups['header']['content'] . PHP_EOL;
415 $content .= $this->getContent();
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);
431 // Something went wrong
432 $this->debugInstance(__METHOD__ . '(): Something unexpected happened here.');
436 // Is footer content there?
437 if (isset($this->groups['footer'])) {
439 $content .= $this->groups['footer']['content'] . PHP_EOL;
443 //* DEBUG: */ echo "content=<pre>".htmlentities($content)."</pre> (".strlen($content).")<br />\n";
448 * Checks whether the specified group is opened
450 * @param $groupId Id of group to check
451 * @return $isOpened Whether the specified group is open
453 protected function ifGroupIsOpened (string $groupId) {
454 // Is the group open?
455 $isOpened = ((isset($this->groups[$groupId])) && ($this->groups[$groupId]['opened'] === true));
462 * Getter for direct field values
464 * @param $fieldName Name of the field we shall fetch
465 * @return $fieldValue Value from field
466 * @throws NullPointerException Thrown if $valueInstance is null
468 public function getValueField (string $fieldName) {
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);
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!');
489 $this->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] fieldName=' . $fieldName . ' is not set! - @TODO');
497 * Getter for value instance
499 * @return $valueInstance Instance of the class holding our values
501 public final function getValueInstance () {
502 return $this->valueInstance;
506 * Check whether a group was opened previously
508 * @return $groupOpened Whether any group was opened before
510 protected final function ifGroupOpenedPreviously () {
511 $groupOpened = (!empty($this->previousGroupId));
516 * Check whether a group was opened previously
518 * @return $subGroupOpened Whether any group was opened before
520 protected final function ifSubGroupOpenedPreviously () {
521 $subGroupOpened = (!empty($this->previousSubGroupId));
522 return $subGroupOpened;
526 * Getter for previous group id
528 * @return $previousGroupId Id of previously opened group
530 protected final function getPreviousGroupId () {
531 return $this->previousGroupId;
535 * Setter for previous group id
537 * @param $previousGroupId Id of previously opened group
540 protected final function setPreviousGroupId (string $previousGroupId) {
541 $this->previousGroupId = $previousGroupId;
545 * Getter for previous sub group id
547 * @return $previousSubGroupId Id of previously opened sub group
549 protected final function getPreviousSubGroupId () {
550 return $this->previousSubGroupId;
554 * Setter for previous sub group id
556 * @param $previousSubGroupId Id of previously opened sub group
559 protected final function setPreviousSubGroupId (string $previousSubGroupId) {
560 $this->previousSubGroupId = $previousSubGroupId;