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