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