3 * A generic helper class with generic methods
5 * @author Roland Haeder <webmaster@shipsimu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.shipsimu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class BaseHelper extends BaseFrameworkSystem {
26 * Instance to the class which provides field values
28 private $valueInstance = NULL;
31 * Extra instance to the class which provides field values
33 private $extraInstance = NULL;
36 * Rendered content created by the helper class
38 private $content = '';
43 private $groups = array();
46 * Array with sub group
48 private $subGroups = array();
51 * Previously opened group
53 private $previousGroupId = '';
56 * Previously opened sub group
58 private $previousSubGroupId = '';
61 * Total counter for groups and sub groups
63 private $totalCounter = 0;
65 // Exception constants
66 const EXCEPTION_GROUP_NOT_OPENED = 0x1e3;
67 const EXCEPTION_GROUP_ALREADY_FOUND = 0x1e4;
68 const EXCEPTION_SUB_GROUP_ALREADY_FOUND = 0x1e5;
69 const EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED = 0x1e6;
70 const EXCEPTION_NO_PREVIOUS_GROUP_OPENED = 0x1e7;
73 * Protected constructor
75 * @param $className Real name of the class
78 protected function __construct ($className) {
79 // Call parent constructor
80 parent::__construct($className);
84 * Adds content directly
86 * @param $newContent New content to add
89 protected final function addContent ($newContent) {
90 $this->content .= (string) trim($newContent) . PHP_EOL;
94 * Add header content to the helper
96 * @param $content Content to to the base
99 protected function addHeaderContent ($content) {
100 // Add the header content
101 $this->groups['header']['content'] = (string) trim($content);
105 * Add footer content to the helper
107 * @param $content Content to to the base
110 protected function addFooterContent ($content) {
111 // Add the footer content
112 $this->groups['footer']['content'] = (string) trim($content);
116 * Adds content to the previously opened group or sub group. If a sub group
117 * was found it will be taken. If no group/sub group is opened at the moment
118 * the code will be passed to addContent().
120 * @param $newContent New content to add
123 protected final function addContentToPreviousGroup ($newContent) {
124 // Check for sub/group
125 if ($this->ifSubGroupOpenedPreviously()) {
127 $subGroupId = $this->getPreviousSubGroupId();
130 $this->subGroups[$subGroupId]['content'] .= $newContent;
131 } elseif ($this->ifGroupOpenedPreviously()) {
133 $groupId = $this->getPreviousGroupId();
136 $this->groups[$groupId]['content'] .= $newContent;
139 $this->addContent($newContent);
146 * @return $content The rendered content by this helper
148 protected final function getContent () {
149 return $this->content;
153 * Public setter for extra instance
155 * @param $extraInstance An extra instance of FrameworkInterface to set
158 public final function setExtraInstance (FrameworkInterface $extraInstance) {
159 $this->extraInstance = $extraInstance;
163 * Assigns a field from the value instance with a template variable
165 * @param $fieldName Name of the field to assign
168 public function assignField ($fieldName) {
169 // Get the value from value instance
170 $fieldValue = $this->getValueField($fieldName);
172 // Assign it with a template variable
173 $this->getTemplateInstance()->assignVariable('block_' . $fieldName, $fieldValue);
177 * Assigns a field from the value instance with a template variable but
178 * parses its content through a given filter method of the value instance
180 * @param $fieldName Name of the field to assign
181 * @param $filterMethod Method name to call of the value instance
183 * @todo Rewrite this method using a helper class for filtering data
185 public function assignFieldWithFilter ($fieldName, $filterMethod) {
187 $fieldValue = $this->getValueField($fieldName);
188 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.'='.$fieldValue);
190 // Now filter it through the value through the filter method
191 $filteredValue = call_user_func_array(array($this, 'doFilter' . self::convertToClassName($filterMethod)), array($fieldValue));
193 // Assign it with a template variable
194 $this->getTemplateInstance()->assignVariable('block_' . $fieldName, $filteredValue);
198 * Pre-fetches field default values from the given registry key instance into this class
200 * @param $registryKey Registry key which holds an object with values
201 * @param $extraKey Extra value instance key used if registryKey is null
203 * @throws NullPointerException If recovery of requested value instance failed
205 public function prefetchValueInstance ($registryKey, $extraKey = NULL) {
206 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('O:'.$registryKey.'/'.$extraKey);
208 // Get the required instance
209 $this->valueInstance = Registry::getRegistry()->getInstance($registryKey);
210 } catch (NullPointerException $e) {
211 // Not set in registry
212 // @TODO Try to log it here
213 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($registryKey.'=NULL!');
216 // Shall we get an extra instance?
217 if (!is_null($extraKey)) {
219 // Get the extra instance.
220 $this->extraInstance = Registry::getRegistry()->getInstance($extraKey);
221 } catch (NullPointerException $e) {
223 $this->extraInstance = ObjectFactory::createObjectByConfiguredName($extraKey . '_class', array($this->valueInstance));
225 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($extraKey.'='.$this->extraInstance.' - EXTRA!');
228 // Is the value instance valid?
229 if (is_null($this->valueInstance)) {
230 // Get the requested instance
231 $this->valueInstance = ObjectFactory::createObjectByConfiguredName($registryKey . '_class', array($this->extraInstance));
236 * Opens a helper group with given group id and content or throws an
237 * exception if that group is already found regardless if it is open or
240 * @param $groupId Group id to open
241 * @param $content Initial content to add to the group
242 * @param $tag HTML tag used to open this group
244 * @throws HelperGroupAlreadyCreatedException If the group was already created before
246 protected function openGroupByIdContent ($groupId, $content, $tag) {
247 //* DEBUG: */ echo "OPEN:groupId={$groupId},content=<pre>".htmlentities($content)."</pre>\n";
248 // Is the group already there?
249 if (isset($this->groups[$groupId])) {
250 // Then throw an exception here
251 throw new HelperGroupAlreadyCreatedException(array($this, $groupId), self::EXCEPTION_GROUP_ALREADY_FOUND);
255 $this->totalCounter++;
257 // Add the group to the stack
258 $this->groups[$this->totalCounter] = $groupId;
259 $this->groups[$groupId]['opened'] = TRUE;
260 $this->groups[$groupId]['content'] = sprintf(
261 '<!-- group %s opened (length: %s, tag: %s) //-->%s' . PHP_EOL,
267 $this->groups[$groupId]['tag'] = $tag;
269 // Mark this group as previously opened
270 $this->setPreviousGroupId($groupId);
274 * Closes the previously opened group by added given content to it or
275 * throws an exception if no previous group was opened
277 * @param $content Content for previously opened group, or empty to use tag of opener
279 * @throws HelperNoPreviousOpenedGroupException If no previously opened group was found
281 public function closePreviousGroupByContent ($content = '') {
282 // Check if any sub group was opened before
283 if ($this->ifSubGroupOpenedPreviously()) {
284 // Close it automatically
285 $this->closePreviousSubGroupByContent();
288 // Check if any group was opened before
289 if ($this->ifGroupOpenedPreviously() === FALSE) {
290 // Then throw an exception
291 throw new HelperNoPreviousOpenedGroupException(array($this, $content), self::EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED);
294 // Get previous group
295 $groupId = $this->getPreviousGroupId();
297 // Is the content empty?
298 if ((empty($content)) && (!empty($this->groups[$groupId]['tag']))) {
299 // Get it from opener
301 "<!-- group %s auto-closed //--></%s>",
303 $this->groups[$groupId]['tag']
307 // Add content to it and mark it as closed
308 $this->groups[$groupId]['content'] .= sprintf(
309 "<!-- group %s closed (length: %s, tag: %s) //-->%s\n",
312 $this->groups[$groupId]['tag'],
315 $this->groups[$groupId]['opened'] = FALSE;
317 // Mark previous group as closed
318 $this->setPreviousGroupId('');
319 //* DEBUG: */ echo "CLOSE:groupId={$groupId}<br />\n";
323 * Opens a helper sub group with given group id and content or throws an
324 * exception if that sub group is already found regardless if it is open or
327 * @param $subGroupId Sub group id to open
328 * @param $content Initial content to add to the sub group
329 * @param $tag HTML tag used to open this group
331 * @throws HelperSubGroupAlreadyCreatedException If the sub group was already created before
333 protected function openSubGroupByIdContent ($subGroupId, $content, $tag) {
334 //* DEBUG: */ echo "OPEN:subGroupId={$subGroupId},content=".htmlentities($content)."<br />\n";
335 // Is the group already there?
336 if (isset($this->subGroups[$subGroupId])) {
337 // Then throw an exception here
338 throw new HelperSubGroupAlreadyCreatedException(array($this, $subGroupId), self::EXCEPTION_SUB_GROUP_ALREADY_FOUND);
342 $this->totalCounter++;
344 // Add the group to the stack
345 $this->subGroups[$this->totalCounter] = $subGroupId;
346 $this->subGroups[$subGroupId]['opened'] = TRUE;
347 $this->subGroups[$subGroupId]['content'] = sprintf("<!-- sub-group %s opened (length: %s, tag: %s) //-->%s\n", $subGroupId, strlen($content), $tag, $content);
348 $this->subGroups[$subGroupId]['tag'] = $tag;
350 // Mark this group as previously opened
351 $this->setPreviousSubGroupId($subGroupId);
355 * Closes the previously opened sub group by added given content to it or
356 * throws an exception if no previous sub group was opened
358 * @param $content Content for previously opened sub group, or leave empty to use div/span of openener
360 * @throws HelperNoPreviousOpenedSubGroupException If no previously opened sub group was found
362 public function closePreviousSubGroupByContent ($content = '') {
363 // Check if any sub group was opened before
364 if ($this->ifSubGroupOpenedPreviously() === FALSE) {
365 // Then throw an exception
366 throw new HelperNoPreviousOpenedSubGroupException(array($this, $content), self::EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED);
369 // Get previous sub group
370 $subGroupId = $this->getPreviousSubGroupId();
372 // Is the content empty?
373 if ((empty($content)) && (!empty($this->subGroups[$subGroupId]['tag']))) {
374 // Get it from opener
375 $content = sprintf('<!-- sub-group %s auto-closed //--></%s>', $subGroupId, $this->subGroups[$subGroupId]['tag']);
378 // Add content to it and mark it as closed
379 $this->subGroups[$subGroupId]['content'] .= sprintf('<!-- sub-group %s closed (length: %s, tag: %s) //-->%s' . PHP_EOL, $subGroupId, strlen($content), $this->subGroups[$subGroupId]['tag'], $content);
380 $this->subGroups[$subGroupId]['opened'] = FALSE
383 // Mark previous sub group as closed
384 $this->setPreviousSubGroupId('');
385 //* DEBUG: */ echo "CLOSE:subGroupId={$subGroupId}<br />\n";
389 * Renders all group and sub group in their order
391 * @return $content Rendered HTML content
393 public function renderContent () {
394 // Initialize content
397 // Is header content there?
398 if (isset($this->groups['header'])) {
400 $content .= $this->groups['header']['content'] . PHP_EOL;
404 $content .= $this->getContent();
406 // Now "walk" through all groups and sub-groups
407 for ($idx = 1; $idx <= $this->totalCounter; $idx++) {
408 // Is this a sub/group and is it closed?
409 if ((isset($this->groups[$idx])) && ($this->groups[$this->groups[$idx]]['opened'] === FALSE)) {
410 // Then add it's content
411 $groupContent = trim($this->groups[$this->groups[$idx]]['content']);
412 //* DEBUG: */ echo "group={$this->groups[$idx]},content=<pre>".htmlentities($groupContent)."</pre><br />\n";
413 $content .= $groupContent;
414 } elseif ((isset($this->subGroups[$idx])) && ($this->subGroups[$this->subGroups[$idx]]['opened'] === FALSE)) {
415 // Then add it's content
416 $subGroupContent = $this->subGroups[$this->subGroups[$idx]]['content'];
417 //* DEBUG: */ echo "subgroup={$this->subGroups[$idx]},content=<pre>".htmlentities($subGroupContent)."</pre><br />\n";
418 $content .= trim($subGroupContent);
420 // Something went wrong
421 $this->debugInstance(__METHOD__ . '(): Something unexpected happened here.');
425 // Is footer content there?
426 if (isset($this->groups['footer'])) {
428 $content .= $this->groups['footer']['content'] . PHP_EOL;
432 //* DEBUG: */ echo "content=<pre>".htmlentities($content)."</pre> (".strlen($content).")<br />\n";
437 * Checks whether the specified group is opened
439 * @param $groupId Id of group to check
440 * @return $isOpened Whether the specified group is open
442 protected function ifGroupIsOpened ($groupId) {
443 // Is the group open?
444 $isOpened = ((isset($this->groups[$groupId])) && ($this->groups[$groupId]['opened'] === TRUE));
451 * Getter for direct field values
453 * @param $fieldName Name of the field we shall fetch
454 * @return $fieldValue Value from field
455 * @throws NullPointerException Thrown if $valueInstance is null
457 public function getValueField ($fieldName) {
461 // The $valueInstance attribute should not be null!
462 if (is_null($this->getValueInstance())) {
463 // Throws an exception here
464 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
468 if ($this->getValueInstance()->isFieldSet($fieldName)) {
469 // Get the field value
470 $fieldValue = $this->getValueInstance()->getField($fieldName);
471 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.'[]='.gettype($fieldValue).'('.strlen($fieldValue).') - Value instance!');
472 } elseif ((!is_null($this->extraInstance)) && ($this->extraInstance->isFieldSet($fieldName))) {
473 // So try the extra instance
474 $fieldValue = $this->extraInstance->getField($fieldName);
475 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.'[]='.gettype($fieldValue).'('.strlen($fieldValue).') - Extra instance!');
478 $this->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] fieldName=' . $fieldName . ' is not set! - @TODO');
486 * Getter for value instance
488 * @return $valueInstance Instance of the class holding our values
490 public final function getValueInstance () {
491 return $this->valueInstance;
495 * Check whether a group was opened previously
497 * @return $groupOpened Whether any group was opened before
499 protected final function ifGroupOpenedPreviously () {
500 $groupOpened = (!empty($this->previousGroupId));
505 * Check whether a group was opened previously
507 * @return $subGroupOpened Whether any group was opened before
509 protected final function ifSubGroupOpenedPreviously () {
510 $subGroupOpened = (!empty($this->previousSubGroupId));
511 return $subGroupOpened;
515 * Getter for previous group id
517 * @return $previousGroupId Id of previously opened group
519 protected final function getPreviousGroupId () {
520 return $this->previousGroupId;
524 * Setter for previous group id
526 * @param $previousGroupId Id of previously opened group
529 protected final function setPreviousGroupId ($previousGroupId) {
530 $this->previousGroupId = (string) $previousGroupId;
534 * Getter for previous sub group id
536 * @return $previousSubGroupId Id of previously opened sub group
538 protected final function getPreviousSubGroupId () {
539 return $this->previousSubGroupId;
543 * Setter for previous sub group id
545 * @param $previousSubGroupId Id of previously opened sub group
548 protected final function setPreviousSubGroupId ($previousSubGroupId) {
549 $this->previousSubGroupId = (string) $previousSubGroupId;