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