]> git.mxchange.org Git - core.git/blob - framework/main/classes/iterator/registry/class_RegistryIterator.php
Continued:
[core.git] / framework / main / classes / iterator / registry / class_RegistryIterator.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Iterator\Registry;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
7 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
8 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
9 use Org\Mxchange\CoreFramework\Iterator\BaseIterator;
10 use Org\Mxchange\CoreFramework\Registry\Register;
11 use Org\Mxchange\CoreFramework\Registry\Registerable;
12 use Org\Mxchange\CoreFramework\Registry\Sub\SubRegistry;
13 use Org\Mxchange\CoreFramework\Traits\Registry\RegisterTrait;
14
15 // Import SPL stuff
16 use \BadMethodCallException;
17 use \LogicException;
18 use \UnexpectedValueException;
19
20 /**
21  * A registry iterator
22  *
23  * @author              Roland Haeder <webmaster@ship-simu.org>
24  * @version             0.0.0
25  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
26  * @license             GNU GPL 3.0 or any newer version
27  * @link                http://www.ship-simu.org
28  *
29  * This program is free software: you can redistribute it and/or modify
30  * it under the terms of the GNU General Public License as published by
31  * the Free Software Foundation, either version 3 of the License, or
32  * (at your option) any later version.
33  *
34  * This program is distributed in the hope that it will be useful,
35  * but WITHOUT ANY WARRANTY; without even the implied warranty of
36  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37  * GNU General Public License for more details.
38  *
39  * You should have received a copy of the GNU General Public License
40  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
41  */
42 class RegistryIterator extends BaseIterator implements IteratableRegistry {
43         // Load traits
44         use RegisterTrait;
45
46         /**
47          * All found registry keys
48          */
49         private $registryKeys = [];
50
51         /**
52          * An array containing keys ob sub-registries which keys should only be
53          * included in the iterator.
54          */
55         private $onlyRegistries = [];
56
57         /**
58          * Current array key
59          */
60         private $key = NULL;
61
62         /**
63          * Protected constructor
64          *
65          * @return      void
66          */
67         private function __construct () {
68                 // Call parent constructor
69                 parent::__construct(__CLASS__);
70
71                 // Init registry keys array
72                 $this->registryKeys = [
73                         // Generic registry
74                         'generic' => [],
75                         // Instance registry
76                         'instance' => [],
77                 ];
78         }
79
80         /**
81          * Creates an instance of this class
82          *
83          * @param       $registryInstance       An instance of a Register class
84          * @return      $iteratorInstance       An instance of a Iterator class
85          */
86         public final static function createRegistryIterator (Register $registryInstance) {
87                 // Get new instance
88                 $iteratorInstance = new RegistryIterator();
89
90                 // Set registry here
91                 $iteratorInstance->setRegistryInstance($registryInstance);
92
93                 // Return the prepared instance
94                 return $iteratorInstance;
95         }
96
97         /**
98          * Setter for only-registries array
99          *
100          * @param       $onlyRegistries         Array with keys only being iterated over
101          * @return      void
102          */
103         private function setOnlyRegistries (array $onlyRegistries) {
104                 $this->onlyRegistries = $onlyRegistries;
105         }
106
107         /**
108          * Initializes this iterator by scanning over the registry for all keys.
109          *
110          * @param       $onlyRegistries         Only iterate on these sub-registry keys, default is all
111          * @return      void
112          * @throws      LogicException  If a registry entry does not implement Registerable
113          * @throws      NullPointerException    If criteriaKey or criteriaMethod is not set but a call-back instance is set
114          */
115         public function initIterator (array $onlyRegistries = []) {
116                 // Set it in this registry
117                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR: onlyRegistries()=%d - CALLED!', count($onlyRegistries)));
118                 $this->setOnlyRegistries($onlyRegistries);
119
120                 // Get generic registry entries from it
121                 $entries = $this->getRegistryInstance()->getGenericRegistry();
122
123                 // Anything in there?
124                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[generic]: entries()=%d', count($entries)));
125                 if (count($entries) > 0) {
126                         // Debugging:
127                         /* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: UNFINISHED: entries=%s', __METHOD__, __LINE__, print_r($entries, TRUE)));
128                 }
129
130                 // Get instance registry entries from it
131                 $entries = $this->getRegistryInstance()->getInstanceRegistry();
132
133                 // Anything in there?
134                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[instance]: entries()=%d', count($entries)));
135                 if (count($entries) > 0) {
136                         // Then run over all
137                         foreach ($entries as $key => $entry) {
138                                 // Is an unwanted registry found?
139                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[instance]: key=%s,entry[]=%s', $key, gettype($entry)));
140                                 if (substr($key, -8, 8) == 'registry') {
141                                         // Skip this!
142                                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[instance]: key=%s is a registry key, skipping ...', $key));
143                                         continue;
144                                 }
145
146                                 // Is it an instance of a sub-registry?
147                                 if (count($onlyRegistries) > 0 && !in_array($key, $onlyRegistries, TRUE)) {
148                                         // Not in requested registries
149                                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[instance]: key=%s is not wanted, skipping ...', $key));
150                                         continue;
151                                 } elseif ($entry instanceof SubRegistry) {
152                                         // Get iterator from this instance
153                                         $subRegistryInstances = $entry->getInstanceRegistry();
154
155                                         // Add all sub-registry keys to this registry keys array
156                                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[instance]: subRegistryInstances()=%d', count($subRegistryInstances)));
157                                         //* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: key=%s,subRegistryInstances=%s', __METHOD__, __LINE__, $key, print_r($subRegistryInstances, TRUE)));
158                                         foreach (array_keys($subRegistryInstances) as $subKey) {
159                                                 // Add it
160                                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[instance]: Adding key=%s,subKey=%s ...', $key, $subKey));
161                                                 array_push($this->registryKeys['instance'], $subKey);
162
163                                                 // Is the current key set?
164                                                 if (is_null($this->key)) {
165                                                         // Init key
166                                                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[instance]: Setting subKey=%s as first key ...', $subKey));
167                                                         $this->key = $subKey;
168                                                 }
169                                         }
170
171                                         // Skip below code
172                                         continue;
173                                 } elseif (!($entry instanceof Registerable)) {
174                                         // Not registerable?!
175                                         throw new LogicException(sprintf('entry[]=%s does not implement Registerable.', gettype($entry)), FrameworkInterface::EXCEPTION_LOGIC_EXCEPTION);
176                                 }
177
178                                 // Is the current key set?
179                                 if (is_null($this->key)) {
180                                         // Init key
181                                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[instance]: Setting key=%s as first key ...', $key));
182                                         $this->key = $key;
183                                 }
184
185                                 // Add key to array
186                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[instance]: key=%s - Adding ...', $key));
187                                 //* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: key=%s,entry=%s', __METHOD__, __LINE__, $key, print_r($entry, TRUE)));
188                                 array_push($this->registryKeys['instance'], $key);
189                         }
190                 }
191
192                 // Trace message
193                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('REGISTRY-ITERATOR: EXIT!');
194         }
195
196         /**
197          * Getter for all registry keys (array)
198          *
199          * @return      $registryKeys   Registry keys
200          */
201         public final function getRegistryKeys () {
202                 // Return it
203                 return $this->registryKeys;
204         }
205
206         /**
207          * Getter for current value from group or generic
208          *
209          * @return      $current        Current value in iteration
210          * @throws      NullPointerException    If current key points to a non-existing entry in searched registries
211          */
212         public function current () {
213                 // Default is null
214                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: CALLED!', $this->key()));
215                 //* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this->key(%d)[%s]=%s,this->valid=%d,this->registryKeys=%s', __METHOD__, __LINE__, strlen($this->key()), gettype($this->key()), $this->key(), intval($this->valid()), print_r($this->registryKeys, TRUE)));
216                 $current = NULL;
217                 $entries = [];
218
219                 // Get all registries
220                 $allRegistries = $this->getRegistryInstance()->getInstanceRegistry();
221
222                 // Loop through all sub-sets
223                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: allRegistries()=%d', $this->key(), count($allRegistries)));
224                 foreach ($allRegistries as $registryKey => $registryInstance) {
225                         // Is this key wanted?
226                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: registryKey=%s', $this->key(), $registryKey));
227                         if (count($this->onlyRegistries) == 0 || in_array($registryKey, $this->onlyRegistries)) {
228                                 // Yes, then loop through them only
229                                 $instances = $registryInstance->getInstanceRegistry();
230
231                                 // The key should be there
232                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: Handling registryKey=%s ...', $this->key(), $registryKey));
233                                 //* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: instances=%s', __METHOD__, __LINE__, print_r($instances, TRUE)));
234                                 if (!isset($instances[$this->key()])) {
235                                         // Skip below code
236                                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: registryKey=%s has no this->key=%s, skipping ...', $this->key(), $registryKey, $this->key()));
237                                         continue;
238                                 }
239
240                                 // Set as current element and leave loop
241                                 $current = $instances[$this->key()];
242                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: registryKey=%s,current=%s found. - BREAK!', $this->key(), $registryKey, $current->__toString()));
243                                 break;
244                         }
245                 }
246
247                 // Is current still NULL?
248                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: registryKey=%s,current[]=%s', $this->key(), $registryKey, gettype($current)));
249                 if (is_null($current)) {
250                         // This cannot happen and indicates a logic error
251                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
252                 }
253
254                 // Return it
255                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: current[%s]=%s - EXIT!', $this->key(), gettype($current), $current));
256                 return $current;
257         }
258
259         /**
260          * Getter for key from group or generic
261          *
262          * @return      $key    Current key in iteration
263          */
264         public function key () {
265                 // Return it
266                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR: this->key=%s EXIT!', $this->key));
267                 return $this->key;
268         }
269
270         /**
271          * Advances to the next entry
272          *
273          * @return      void
274          * @throws      BadMethodCallException  If $this->valid() returns FALSE
275          * @throws      UnexpectedValueException        If $registryType is not changed
276          */
277         public function next () {
278                 // Is valid() still TRUE?
279                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: CALLED!', $this->key()));
280                 //* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this->key(%d)[%s]=%s,this->valid=%d,this->registryKeys=%s', __METHOD__, __LINE__, strlen($this->key()), gettype($this->key()), $this->key(), intval($this->valid()), print_r($this->registryKeys, TRUE)));
281                 if (!$this->valid()) {
282                         // Bad method call!
283                         throw new BadMethodCallException(sprintf('this->key[%s]=%s is no longer valid, but method was called.', gettype($this->key()), $this->key()), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
284                 } elseif ((count($this->registryKeys['generic']) == 0) && (count($this->registryKeys['instance']) == 0)) {
285                         // Both arrays are empty
286                         throw new BadMethodCallException('No array elements in "generic" and "instance" found but method called.', FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
287                 }
288
289                 // Default is not valid
290                 $nextIndex = -1;
291                 $isNextValid = FALSE;
292                 $registryType = 'invalid';
293
294                 // Get first array element ...
295                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: this->registryKeys[generic]()=%d,this->registryKeys[instance]()=%d', $this->key(), count($this->registryKeys['generic']), count($this->registryKeys['instance'])));
296                 if (count($this->registryKeys['generic']) > 0) {
297                         // First generic array
298                         /* UNFINISHED */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this->key(%d)[%s]=%s,this->valid=%d,this->registryKeys=%s', __METHOD__, __LINE__, strlen($this->key()), gettype($this->key()), $this->key(), intval($this->valid()), print_r($this->registryKeys, TRUE)));
299                 } elseif (count($this->registryKeys['instance']) > 0) {
300                         // Second instance, current key's index + 1
301                         $nextIndex = array_search($this->key(), $this->registryKeys['instance']) + 1;
302                         $isNextValid = isset($this->registryKeys['instance'][$nextIndex]);
303                         $registryType = 'instance';
304                 }
305
306                 // Is it still valid?
307                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: isNextValid=%d', $this->key(), intval($isNextValid)));
308                 if (!$isNextValid) {
309                         // Throw exception
310                         throw new BadMethodCallException(sprintf('this->key=%s is last key in this iteration. Forgot to invoke valid() before?', $this->key()), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
311                 } elseif ($registryType == 'invalid') {
312                         // Not changed!
313                         throw new UnexpectedValueException('registryType has not been changed.', FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
314                 }
315
316                 // Yes, then advance to that entry
317                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR: Setting this->key from this->registryKeys[%s][%d] ...', $registryType, $nextIndex));
318                 $this->key = $this->registryKeys[$registryType][$nextIndex];
319
320                 // Trace message
321                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: EXIT!', $this->key()));
322         }
323
324         /**
325          * Rewinds to the beginning of the iteration
326          *
327          * @return      void
328          * @throws      BadMethodCallException  If $this->key is already the first element
329          */
330         public function rewind () {
331                 // Is current key first key?
332                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: CALLED!', $this->key()));
333                 //* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this->key(%d)[%s]=%s,this->valid=%d,this->registryKeys=%s', __METHOD__, __LINE__, strlen($this->key()), gettype($this->key()), $this->key(), intval($this->valid()), print_r($this->registryKeys, TRUE)));
334                 if (array_search($this->key(), $this->getRegistryKeys()) === 0) {
335                         // rewind() cannot rewind first entry!
336                         throw new BadMethodCallException(sprintf('this->key=%s is already first element, but method was called.', $this->key()), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
337                 } elseif ((count($this->registryKeys['generic']) == 0) && (count($this->registryKeys['instance']) == 0)) {
338                         // Both arrays are empty
339                         throw new BadMethodCallException('No array elements in "generic" and "instance" found but method called.', FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
340                 }
341
342                 // Get first array element ...
343                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: this->registryKeys[generic]()=%d,this->registryKeys[instance]()=%d', $this->key(), count($this->registryKeys['generic']), count($this->registryKeys['instance'])));
344                 if (count($this->registryKeys['generic']) > 0) {
345                         // First generic array
346                         /* UNFINISHED */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this->key(%d)[%s]=%s,this->valid=%d,this->registryKeys=%s', __METHOD__, __LINE__, strlen($this->key()), gettype($this->key()), $this->key(), intval($this->valid()), print_r($this->registryKeys, TRUE)));
347                 } elseif (count($this->registryKeys['instance']) > 0) {
348                         // Second instance
349                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('REGISTRY-ITERATOR: Setting this->key from this->registryKeys[instance][0] ...');
350                         $this->key = $this->registryKeys['instance'][0];
351                 }
352
353                 // Trace message
354                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: EXIT!', $this->key()));
355         }
356
357         /**
358          * Checks wether the current entry is valid (not at the end of the list)
359          *
360          * @return      $valid  Whether the current key is still valid
361          */
362         public function valid () {
363                 // Is the element there?
364                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: CALLED!', $this->key()));
365                 //* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this->key(%d)[%s]=%s,this->registryKeys=%s', __METHOD__, __LINE__, strlen($this->key()), gettype($this->key()), $this->key(), print_r($this->registryKeys, TRUE)));
366                 $valid = (in_array($this->key(), $this->registryKeys['instance']) || in_array($this->key(), $this->registryKeys['generic']));
367
368                 // Return flag
369                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: valid=%d - EXIT!', $this->key(), intval($valid)));
370                 return $valid;
371         }
372
373 }