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