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