Renamed Registry -> GenericRegistry to make it clear that this registry does
[core.git] / framework / main / classes / lists / class_BaseList.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Lists;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
7 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
8 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
9 use Org\Mxchange\CoreFramework\Visitor\Visitable;
10
11 // Import SPL stuff
12 use \IteratorAggregate;
13 use \Countable;
14
15 /**
16  * A general list class
17  *
18  * @author              Roland Haeder <webmaster@shipsimu.org>
19  * @version             0.0.0
20  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
21  * @license             GNU GPL 3.0 or any newer version
22  * @link                http://www.shipsimu.org
23  *
24  * This program is free software: you can redistribute it and/or modify
25  * it under the terms of the GNU General Public License as published by
26  * the Free Software Foundation, either version 3 of the License, or
27  * (at your option) any later version.
28  *
29  * This program is distributed in the hope that it will be useful,
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
32  * GNU General Public License for more details.
33  *
34  * You should have received a copy of the GNU General Public License
35  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
36  */
37 abstract class BaseList extends BaseFrameworkSystem implements IteratorAggregate, Countable {
38         // Exception constants
39         const EXCEPTION_GROUP_ALREADY_ADDED = 0xf20;
40         const EXCEPTION_GROUP_NOT_FOUND     = 0xf21;
41         const EXCEPTION_INVALID_HASH        = 0xf22;
42
43         /**
44          * List groups array
45          */
46         private $listGroups = array();
47
48         /**
49          * List entries array
50          */
51         private $listEntries = array();
52
53         /**
54          * List index array
55          */
56         private $listIndex = array();
57
58         /**
59          * Protected constructor
60          *
61          * @param       $className      Name of the class
62          * @return      void
63          */
64         protected function __construct ($className) {
65                 // Call parent constructor
66                 parent::__construct($className);
67         }
68
69         /**
70          * Getter for iterator instance from this list
71          *
72          * @return      $iteratorInstance       An instance of a Iterator class
73          */
74         public function getIterator () {
75                 // Get iterator from here
76                 $iteratorInstance = $this->getIteratorInstance();
77
78                 // Is the instance set?
79                 if (is_null($iteratorInstance)) {
80                         // Prepare a default iterator
81                         $iteratorInstance = ObjectFactory::createObjectByConfiguredName('default_iterator_class', array($this));
82
83                         // Set it here
84                         $this->setIteratorInstance($iteratorInstance);
85                 } // END - if
86
87                 // And return it
88                 return $iteratorInstance;
89         }
90
91         /**
92          * Checks whether the given group is set
93          *
94          * @param       $groupName      Group to check if found in list
95          * @return      $isset          Whether the group is valid
96          */
97         public function isGroupSet ($groupName) {
98                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName);
99                 return isset($this->listGroups[$groupName]);
100         }
101
102         /**
103          * Adds the given group or if already added issues a ListGroupAlreadyAddedException
104          *
105          * @param       $groupName      Group to add
106          * @return      void
107          * @throws      ListGroupAlreadyAddedException  If the given group is already added
108          */
109         public function addGroup ($groupName) {
110                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ' - CALLED!');
111                 // Is the group already added?
112                 if ($this->isGroupSet($groupName)) {
113                         // Throw the exception here
114                         throw new ListGroupAlreadyAddedException(array($this, $groupName), self::EXCEPTION_GROUP_ALREADY_ADDED);
115                 } // END - if
116
117                 // Add the group which is a simple array
118                 $this->listGroups[$groupName] = ObjectFactory::createObjectByConfiguredName('list_group_class');
119                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ' - EXIT!');
120         }
121
122         /**
123          * Adds the given instance to list group and sub group
124          *
125          * @param       $groupName                      Group to add instance to
126          * @param       $subGroup                       Sub group to add instance to
127          * @param       $visitableInstance      An instance of Visitable
128          * @return      void
129          * @throws      NoListGroupException    If the given group is not found
130          */
131         public function addInstance ($groupName, $subGroup, Visitable $visitableInstance) {
132                 // Debug message
133                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName  . ',subGroup=' . $subGroup . ',visitableInstance=' . $visitableInstance->__toString() . ' - CALLED!');
134
135                 // Is the group there?
136                 if (!$this->isGroupSet($groupName)) {
137                         // Throw the exception here
138                         throw new NoListGroupException(array($this, $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
139                 } // END - if
140
141                 // Is the sub group there?
142                 if (!$this->listGroups[$groupName]->isGroupSet($subGroup)) {
143                         // Automatically add it
144                         $this->listGroups[$groupName]->addGroup($subGroup);
145                 } // END - if
146
147                 // Generate the hash
148                 $hash = $this->generateHash($groupName, $subGroup, $visitableInstance);
149
150                 // Debug message
151                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',this->listGroups[' . $groupName . ']=' . $this->listGroups[$groupName]->__toString());
152
153                 // Add the hash to the index
154                 array_push($this->listIndex, $hash);
155
156                 // Add the instance itself to the list
157                 $this->listEntries[$hash] = $visitableInstance;
158
159                 // Debug message
160                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName  . ',subGroup=' . $subGroup . ' - EXIT!');
161         }
162
163         /**
164          * Gets an array from given list
165          *
166          * @param       $list   The requested list
167          * @return      $array  The requested array
168          * @throws      NoListGroupException    If the given group is not found
169          */
170         public final function getArrayFromList ($list) {
171                 // Debug message
172                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',list[' . gettype($list) . ']=' . $list . ' - CALLED!');
173
174                 // Is the group there?
175                 if ((!is_null($list)) && (!$this->isGroupSet($list))) {
176                         // Throw the exception here
177                         throw new NoListGroupException(array($this, $list), self::EXCEPTION_GROUP_NOT_FOUND);
178                 } // END - if
179
180                 // Init array
181                 $array = array();
182
183                 // Is there another list?
184                 if (!is_null($list)) {
185                         // Then get it as well
186                         $array = $this->listGroups[$list]->getArrayFromList(NULL);
187                 } // END - if
188
189                 // Walk through all entries
190                 foreach ($this->listIndex as $hash) {
191                         // Debug message
192                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: hash=' . $hash);
193
194                         // Is the list entry set?
195                         if ($this->isHashValid($hash)) {
196                                 // Add it
197                                 array_push($array, $this->listEntries[$hash]);
198                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: hash=' . $hash . ',array(' . count($array) . ')=' . print_r($array, true) . ' - ADDED!');
199                         } // END - if
200                 } // END - foreach
201
202                 // Debug message
203                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',list[' . gettype($list) . ']=' . $list . ',array()=' . count($array) . ' - EXIT!');
204
205                 // Return it
206                 return $array;
207         }
208
209         /**
210          * Adds the given entry to list group
211          *
212          * @param       $groupName      Group to add instance to
213          * @param       $entry          An entry of any type
214          * @return      void
215          * @throws      NoListGroupException    If the given group is not found
216          */
217         public function addEntry ($groupName, $entry) {
218                 // Debug message
219                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ' - CALLED!');
220
221                 // Is the group already added?
222                 if (!$this->isGroupSet($groupName)) {
223                         // Throw the exception here
224                         throw new NoListGroupException(array($this, $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
225                 } // END - if
226
227                 // Generate hash
228                 $hash = $this->generateHash($groupName, $groupName, $entry);
229
230                 // Debug message
231                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ',entry=' . print_r($entry, true) . ', hash=' . $hash);
232
233                 // Add the hash to the index
234                 array_push($this->listIndex, $hash);
235
236                 // Debug message
237                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ',listEntries()=' . count($this->listEntries));
238
239                 // Now add the entry to the list
240                 $this->listEntries[$hash] = $entry;
241
242                 // Debug message
243                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ',listEntries()=' . count($this->listEntries) . ' - EXIT!');
244         }
245
246         /**
247          * Removes given entry from the list group
248          *
249          * @param       $groupName      Group where we should remove the entry from
250          * @param       $entry          The entry we should remove
251          * @return      void
252          * @throws      NoListGroupException    If the given group is not found
253          */
254         public function removeEntry ($groupName, $entry) {
255                 // Debug message
256                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ' - CALLED!');
257
258                 // Is the group already added?
259                 if (!$this->isGroupSet($groupName)) {
260                         // Throw the exception here
261                         throw new NoListGroupException(array($this, $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
262                 } // END - if
263
264                 // Generate hash
265                 $hash = $this->generateHash($groupName, $groupName, $entry);
266
267                 // Debug message
268                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ',entry=' . $entry . ', hash=' . $hash);
269
270                 // Remove it from the list ...
271                 unset($this->listEntries[$hash]);
272
273                 // ... and hash list as well
274                 unset($this->listIndex[array_search($hash, $this->listIndex)]);
275
276                 // Debug message
277                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ' - EXIT!');
278         }
279
280         /**
281          * Generates a hash from given group, sub group and entry
282          *
283          * @param       $groupName      Group to add instance to
284          * @param       $subGroup       Sub group to add instance to
285          * @param       $entry          An entry of any type
286          * @return      $hash           The generated
287          */
288         private function generateHash ($groupName, $subGroup, $entry) {
289                 // Created entry, 'null' is default
290                 $entry2 = 'null';
291
292                 // Determine type of entry
293                 if (is_null($entry)) {
294                         // Ignore this
295                 } elseif ($entry instanceof FrameworkInterface) {
296                         // Own instance detected
297                         $entry2 = $entry->hashCode();
298                 } elseif ((is_int($entry)) || (is_float($entry)) || (is_resource($entry))) {
299                         // Integer/float/resource detected
300                         $entry2 = gettype($entry) . ':' . $entry;
301                 } elseif (is_string($entry)) {
302                         // String found
303                         $entry2 = crc32($entry) . ':' . strlen($entry);
304                 } elseif ((is_array($entry)) && (isset($entry['id']))) {
305                         // Supported array found
306                         $entry2 = crc32($entry['id']) . ':' . count($entry);
307                 } elseif (($this->getCallbackInstance() instanceof FrameworkInterface) && (method_exists($this->getCallbackInstance(), 'generateListHashFromEntry'))) {
308                         // Call it instead
309                         $entry2 = $this->getCallbackInstance()->generateListHashFromEntry($entry);
310                 } else {
311                         // Unsupported type detected
312                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST[' . __METHOD__ . ':' . __LINE__ . ']: Entry type ' . gettype($entry) . ' is unsupported (this->callbackInstance=' . $this->getCallbackInstance() . ').');
313
314                         // At least take all keys from array
315                         $entry2 = gettype($entry) . ':' . implode(':', array_keys($entry));
316                 }
317
318                 // Construct string which we shall hash
319                 $hashString = $groupName . ':' . $subGroup . ':' . $entry2;
320
321                 // Hash it with fastest hasher
322                 $hash = crc32($hashString);
323
324                 // And return it
325                 return $hash;
326         }
327
328         /**
329          * Clears an array of groups, all are being checked for existence
330          *
331          * @param       $groupNames             An array with existing list groups
332          * @return      void
333          */
334         protected function clearGroups (array $groupNames) {
335                 // Walk through all groups
336                 foreach ($groupNames as $groupName) {
337                         // Clear this group
338                         $this->clearGroup($groupName);
339                 } // END - foreach
340         }
341
342         /**
343          * Clears a single group by resetting it to its initial state (empty array)
344          *
345          * @param       $groupName      Name of an existing group to clear
346          * @return      void
347          */
348         protected function clearGroup ($groupName) {
349                 // Does this group exist?
350                 if (!$this->isGroupSet($groupName)) {
351                         // Throw the exception here
352                         throw new NoListGroupException(array($this, $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
353                 } // END - if
354
355                 // Then clear this group list
356                 $this->listGroups[$groupName]->clearList();
357
358                 // Clear this list
359                 $this->listIndex = array();
360                 $this->listEntries = array();
361         }
362         
363         /**
364          * Counts all entries in this list
365          *
366          * @return      $count  All entries in this list
367          */
368         public final function count () {
369                 return count($this->listIndex);
370         }
371
372         /**
373          * Checks whether the given hash is valid
374          *
375          * @param       $hash           The hash we should validate
376          * @return      $isValid        Whether the given hash is valid
377          */
378         public final function isHashValid ($hash) {
379                 // Check it
380                 $isValid = ((in_array($hash, $this->listIndex)) && (isset($this->listEntries[$hash])));
381
382                 // Return the result
383                 return $isValid;
384         }
385
386         /**
387          * Getter for hash from given hash index
388          *
389          * @param       $hashIndex      Index holding the hash
390          * @return      $hash           The hash
391          */
392         public final function getHash ($hashIndex) {
393                 // Get it ...
394                 $hash = $this->listIndex[$hashIndex];
395
396                 // ... and return it
397                 return $hash;
398         }
399
400         /**
401          * Gets an entry from given hash index
402          *
403          * @param       $hashIndex      The hash index to resolve the mapped entry
404          * @return      $entry          Solved entry from list
405          * @throws      InvalidListHashException        If the solved hash index is invalid
406          */
407         public function getEntry ($hashIndex) {
408                 // Get the hash value
409                 $hash = $this->getHash($hashIndex);
410
411                 // Is the hash valid?
412                 if (!$this->isHashValid($hash)) {
413                         // Throw an exception here
414                         throw new InvalidListHashException(array($this, $hash, $hashIndex), self::EXCEPTION_INVALID_HASH);
415                 } // END - if
416
417                 // Now copy the entry
418                 $entry = $this->listEntries[$hash];
419
420                 // Return it
421                 return $entry;
422         }
423
424         /**
425          * Gets a full array from given group name
426          *
427          * @param       $groupName      The group name to get a list for
428          * @return      $entries        The array with all entries
429          * @throws      NoListGroupException    If the specified group is invalid
430          */
431         public function getArrayFromProtocolInstance ($groupName) {
432                 // Is the group valid?
433                 if (!$this->isGroupSet($groupName)) {
434                         // Throw the exception here
435                         throw new NoListGroupException(array($this, $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
436                 } // END - if
437
438                 // Init the entries' array
439                 $entries = array();
440
441                 // Get an iterator
442                 $iteratorInstance = $this->listGroups[$groupName]->getIterator();
443
444                 // Rewind the iterator for this round
445                 $iteratorInstance->rewind();
446
447                 // Go through all entries
448                 while ($iteratorInstance->valid()) {
449                         // Get key
450                         $entryIndex = $iteratorInstance->key();
451
452                         // ... and the final entry which is the stored instance
453                         $entry = $this->getEntry($entryIndex);
454
455                         // Debug message
456                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('LIST: Adding entry ' . $entry . ' ...');
457
458                         // Add it to the list
459                         $entries[$iteratorInstance->current()] = $entry;
460
461                         // Skip to next one
462                         $iteratorInstance->next();
463                 } // END - while
464
465                 // Return the list
466                 return $entries;
467         }
468
469         /**
470          * Updates the given entry by hash with given array
471          *
472          * @param       $hash           Hash for this entry
473          * @param       $entryArray     Array with entry we should update
474          * @return      void
475          * @throws      InvalidListHashException        If the solved hash index is invalid
476          */
477         public function updateCurrentEntryByHash ($hash, array $entryArray) {
478                 // Is the hash valid?
479                 if (!$this->isHashValid($hash)) {
480                         // Throw an exception here, hashIndex is unknown at this point
481                         throw new InvalidListHashException(array($this, $hash, -999), self::EXCEPTION_INVALID_HASH);
482                 } // END - if
483
484                 // Set the entry
485                 $this->listEntries[$hash] = $entryArray;
486         }
487
488 }