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