Renamed Registry -> GenericRegistry to make it clear that this registry does
[core.git] / framework / main / classes / database / result / class_CachedDatabaseResult.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Result\Database;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
7 use Org\Mxchange\CoreFramework\Criteria\Local\LocalUpdateCriteria;
8 use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
9 use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
10 use Org\Mxchange\CoreFramework\Database\Backend\BaseDatabaseBackend;
11 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
12 use Org\Mxchange\CoreFramework\Result\Update\UpdateableResult;
13
14 // Import SPL stuff
15 use \SeekableIterator;
16
17 /**
18  * A database result class
19  *
20  * @author              Roland Haeder <webmaster@shipsimu.org>
21  * @version             0.0.0
22  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
23  * @license             GNU GPL 3.0 or any newer version
24  * @link                http://www.shipsimu.org
25  *
26  * This program is free software: you can redistribute it and/or modify
27  * it under the terms of the GNU General Public License as published by
28  * the Free Software Foundation, either version 3 of the License, or
29  * (at your option) any later version.
30  *
31  * This program is distributed in the hope that it will be useful,
32  * but WITHOUT ANY WARRANTY; without even the implied warranty of
33  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
34  * GNU General Public License for more details.
35  *
36  * You should have received a copy of the GNU General Public License
37  * along with this program. If not, see <http://www.gnu.org/licenses/>.
38  */
39 class CachedDatabaseResult extends BaseDatabaseResult implements SearchableResult, UpdateableResult, SeekableIterator {
40         // Exception constants
41         const EXCEPTION_INVALID_DATABASE_RESULT = 0x1c0;
42         const EXCEPTION_RESULT_UPDATE_FAILED    = 0x1c1;
43
44         /**
45          * Current position in array
46          */
47         private $currentPos = -1;
48
49         /**
50          * Current row
51          */
52         private $currentRow = NULL;
53
54         /**
55          * Result array
56          */
57         private $resultArray = array();
58
59         /**
60          * Array of out-dated entries
61          */
62         private $outDated = array();
63
64         /**
65          * Affected rows
66          */
67         private $affectedRows = 0;
68
69         /**
70          * Found value
71          */
72         private $foundValue = '';
73
74         /**
75          * Protected constructor
76          *
77          * @return      void
78          */
79         protected function __construct () {
80                 // Call parent constructor
81                 parent::__construct(__CLASS__);
82         }
83
84         /**
85          * Creates an instance of this result by a provided result array
86          *
87          * @param       $resultArray            The array holding the result from query
88          * @return      $resultInstance         An instance of this class
89          */
90         public static final function createCachedDatabaseResult (array $resultArray) {
91                 // Get a new instance
92                 $resultInstance = new CachedDatabaseResult();
93
94                 // Set the result array
95                 $resultInstance->setResultArray($resultArray);
96
97                 // Set affected rows
98                 $resultInstance->setAffectedRows(count($resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS]));
99
100                 // Return the instance
101                 return $resultInstance;
102         }
103
104         /**
105          * Setter for result array
106          *
107          * @param       $resultArray    The array holding the result from query
108          * @return      void
109          */
110         protected final function setResultArray (array $resultArray) {
111                 $this->resultArray = $resultArray;
112         }
113
114         /**
115          * Updates the current entry by given update criteria
116          *
117          * @param       $updateInstance         An instance of an Updateable criteria
118          * @return      void
119          */
120         private function updateCurrentEntryByCriteria (LocalUpdateCriteria $updateInstance) {
121                 // Get the current entry key
122                 $entryKey = $this->key();
123
124                 // Now get the update criteria array and update all entries
125                 foreach ($updateInstance->getUpdateCriteria() as $criteriaKey => $criteriaValue) {
126                         // Update data
127                         $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$entryKey][$criteriaKey] = $criteriaValue;
128
129                         // Mark it as out-dated
130                         $this->outDated[$criteriaKey] = 1;
131                 } // END - foreach
132         }
133
134         /**
135          * "Iterator" method next() to advance to the next valid entry. This method
136          * does also check if result is invalid
137          *
138          * @return      $nextValid      Whether the next entry is valid
139          */
140         public function next () {
141                 // Default is not valid
142                 $nextValid = false;
143
144                 // Is the result valid?
145                 if ($this->valid()) {
146                         // Next entry found, so count one up and cache it
147                         $this->currentPos++;
148                         $this->currentRow = $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos];
149                         $nextValid = true;
150                 } // END - if
151
152                 // Return the result
153                 return $nextValid;
154         }
155
156         /**
157          * Seeks for to a specified position
158          *
159          * @param       $index  Index to seek for
160          * @return      void
161          */
162         public function seek ($index) {
163                 // Rewind to beginning
164                 $this->rewind();
165
166                 // Search for the entry
167                 while (($this->currentPos < $index) && ($this->valid())) {
168                         // Continue on
169                         $this->next();
170                 } // END - while
171         }
172
173         /**
174          * Gives back the current position or null if not found
175          *
176          * @return      $current        Current element to give back
177          */
178         public function current () {
179                 // Default is not found
180                 $current = NULL;
181
182                 // Does the current enty exist?
183                 if (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos])) {
184                         // Then get it
185                         $current = $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos];
186                 } // END - if
187
188                 // Return the result
189                 return $current;
190         }
191
192         /**
193          * Checks if next() and rewind will give a valid result
194          *
195          * @return      $isValid Whether the next/rewind entry is valid
196          */
197         public function valid () {
198                 // By default nothing is valid
199                 $isValid = false;
200
201                 // Debug message
202                 //*NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] this->currentPos=' . $this->currentPos);
203
204                 // Check if all is fine ...
205                 if (($this->ifStatusIsOkay()) && (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][($this->currentPos + 1)])) && (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][0]))) {
206                         // All fine!
207                         $isValid = true;
208                 } // END - if
209
210                 // Return the result
211                 return $isValid;
212         }
213
214         /**
215          * Returns count of entries
216          *
217          * @return      $isValid Whether the next/rewind entry is valid
218          */
219         public function count () {
220                 // Return it
221                 return count($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS]);
222         }
223
224         /**
225          * Determines whether the status of the query was fine (BaseDatabaseBackend::RESULT_OKAY)
226          *
227          * @return      $ifStatusOkay   Whether the status of the query was okay
228          */
229         public function ifStatusIsOkay () {
230                 $ifStatusOkay = ((isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_STATUS])) && ($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_STATUS] === BaseDatabaseBackend::RESULT_OKAY));
231                 //*NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] ifStatusOkay=' . intval($ifStatusOkay));
232                 return $ifStatusOkay;
233         }
234
235         /**
236          * Gets the current key of iteration
237          *
238          * @return      $currentPos     Key from iterator
239          */
240         public function key () {
241                 return $this->currentPos;
242         }
243
244         /**
245          * Rewind to the beginning and clear array $currentRow
246          *
247          * @return      void
248          */
249         public function rewind () {
250                 $this->currentPos = -1;
251                 $this->currentRow = array();
252         }
253
254         /**
255          * Searches for an entry in data result and returns it
256          *
257          * @param       $criteriaInstance       The criteria to look inside the data set
258          * @return      $result                         Found result entry
259          * @todo        0% done
260          */
261         public function searchEntry (LocalSearchCriteria $criteriaInstance) {
262                 $this->debugBackTrace('[' . '[' . __METHOD__ . ':' . __LINE__ . ']:  Unfinished!');
263         }
264
265         /**
266          * Adds an update request to the database result for writing it to the
267          * database layer
268          *
269          * @param       $criteriaInstance       An instance of a updateable criteria
270          * @return      void
271          * @throws      ResultUpdateException   If no result was updated
272          */
273         public function add2UpdateQueue (LocalUpdateCriteria $criteriaInstance) {
274                 // Rewind the pointer
275                 $this->rewind();
276
277                 // Get search criteria
278                 $searchInstance = $criteriaInstance->getSearchInstance();
279
280                 // And start looking for the result
281                 $foundEntries = 0;
282                 while (($this->valid()) && ($foundEntries < $searchInstance->getLimit())) {
283                         // Get next entry
284                         $this->next();
285                         $currentEntry = $this->current();
286
287                         // Is this entry found?
288                         if ($searchInstance->ifEntryMatches($currentEntry)) {
289                                 // Update this entry
290                                 $this->updateCurrentEntryByCriteria($criteriaInstance);
291
292                                 // Count one up
293                                 $foundEntries++;
294                         } // END - if
295                 } // END - while
296
297                 // If no entry is found/updated throw an exception
298                 if ($foundEntries == 0) {
299                         // Throw an exception here
300                         throw new ResultUpdateException($this, self::EXCEPTION_RESULT_UPDATE_FAILED);
301                 } // END - if
302
303                 // Set affected rows
304                 $this->setAffectedRows($foundEntries);
305
306                 // Set update instance
307                 $this->setUpdateInstance($criteriaInstance);
308         }
309
310         /**
311          * Setter for affected rows
312          *
313          * @param       $rows   Number of affected rows
314          * @return      void
315          */
316         public final function setAffectedRows ($rows) {
317                 $this->affectedRows = $rows;
318         }
319
320         /**
321          * Getter for affected rows
322          *
323          * @return      $rows   Number of affected rows
324          */
325         public final function getAffectedRows () {
326                 return $this->affectedRows;
327         }
328
329         /**
330          * Getter for found value of previous found() call
331          *
332          * @return      $foundValue             Found value of previous found() call
333          */
334         public final function getFoundValue () {
335                 return $this->foundValue;
336         }
337
338         /**
339          * Checks whether we have out-dated entries or not
340          *
341          * @return      $needsUpdate    Whether we have out-dated entries
342          */
343         public function ifDataNeedsFlush () {
344                 $needsUpdate = (count($this->outDated) > 0);
345                 return $needsUpdate;
346         }
347
348         /**
349          * Adds registration elements to a given dataset instance
350          *
351          * @param       $criteriaInstance       An instance of a StoreableCriteria class
352          * @return      void
353          */
354         public function addElementsToDataSet (StoreableCriteria $criteriaInstance) {
355                 // Walk only through out-dated columns
356                 foreach ($this->outDated as $key => $dummy) {
357                         // Does this key exist?
358                         //* DEBUG: */ echo "outDated: {$key}<br />\n";
359                         if ($this->find($key)) {
360                                 // Then update it
361                                 $criteriaInstance->addCriteria($key, $this->getFoundValue());
362                         } // END - if
363                 } // END - foreach
364         }
365
366         /**
367          * Find a key inside the result array
368          *
369          * @param       $key    The key we shall find
370          * @return      $found  Whether the key was found or not
371          */
372         public function find ($key) {
373                 // By default nothing is found
374                 $found = false;
375
376                 // Rewind the pointer
377                 $this->rewind();
378
379                 // Walk through all entries
380                 while ($this->valid()) {
381                         // Advance to next entry
382                         $this->next();
383
384                         // Get the whole array
385                         $currentEntry = $this->current();
386
387                         // Is the element there?
388                         if (isset($currentEntry[$key])) {
389                                 // Okay, found!
390                                 $found = true;
391
392                                 // So "cache" it
393                                 $this->foundValue = $currentEntry[$key];
394
395                                 // And stop searching
396                                 break;
397                         } // END - if
398                 } // END - while
399
400                 // Return the result
401                 return $found;
402         }
403
404         /**
405          * Solver for result index value with call-back method
406          *
407          * @param       $databaseColumn         Database column where the index might be found
408          * @param       $wrapperInstance        The wrapper instance to ask for array element
409          * @para        $callBack                       Call-back object for setting the index;
410          *                                                              0=object instance,1=method name
411          * @return      void
412          * @todo        Find a caching way without modifying the result array
413          */
414         public function solveResultIndex ($databaseColumn, DatabaseWrapper $wrapperInstance, array $callBack) {
415                 // By default nothing is found
416                 $indexValue = 0;
417
418                 // Is the element in result itself found?
419                 if ($this->find($databaseColumn)) {
420                         // Use this value
421                         $indexValue = $this->getFoundValue();
422                 } elseif ($this->find($wrapperInstance->getIndexKey())) {
423                         // Use this value
424                         $indexValue = $this->getFoundValue();
425                 }
426
427                 // Set the index
428                 call_user_func_array($callBack, array($indexValue));
429         }
430
431 }