Comment header cosmetics applied
[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          * Protected constructor
56          *
57          * @return      void
58          */
59         protected function __construct () {
60                 // Call parent constructor
61                 parent::__construct(__CLASS__);
62
63                 // Set part description
64                 $this->setObjectDescription("Database result");
65
66                 // Create unique ID number
67                 $this->generateUniqueId();
68
69                 // Clean up a little
70                 $this->removeNumberFormaters();
71                 $this->removeSystemArray();
72         }
73
74         /**
75          * Creates an instance of this result by a provided result array
76          *
77          * @param       $resultArray            The array holding the result from query
78          * @return      $resultInstance         An instance of this class
79          */
80         public final static function createDatabaseResult (array $resultArray) {
81                 // Get a new instance
82                 $resultInstance = new DatabaseResult();
83
84                 // Set the result array
85                 $resultInstance->setResultArray($resultArray);
86
87                 // Return the instance
88                 return $resultInstance;
89         }
90
91         /**
92          * Setter for result array
93          *
94          * @param       $resultArray    The array holding the result from query
95          * @return      void
96          */
97         protected final function setResultArray (array $resultArray) {
98                 $this->resultArray = $resultArray;
99         }
100
101         /**
102          * Updates the current entry by given update criteria
103          *
104          * @param       $updateInstance         An instance of an Updateable criteria
105          * @return      void
106          */
107         private function updateCurrentEntryByCriteria (LocalUpdateCriteria $updateInstance) {
108                 // Get the current entry key
109                 $entryKey = $this->key();
110
111                 // Now get the update criteria array and update all entries
112                 foreach ($updateInstance->getUpdateCriteria() as $criteriaKey=>$criteriaValue) {
113                         // Update data
114                         $this->resultArray['rows'][$entryKey][$criteriaKey] = $criteriaValue;
115
116                         // Mark it as out-dated
117                         $this->outDated[$criteriaKey] = 1;
118                 } // END - foreach
119         }
120
121         /**
122          * "Iterator" method next() to advance to the next valid entry. This method
123          * does also check if the result is invalid
124          *
125          * @return      $nextValid      Wether the next entry is valid
126          */
127         public function next () {
128                 // Default is not valid
129                 $nextValid = false;
130
131                 // Is the result valid?
132                 if ($this->resultArray['status'] === "ok") {
133                         // The status is fine so let's have a look for the next entry
134                         if ($this->valid()) {
135                                 // Next entry found, so count one up and cache it
136                                 $this->currentPos++;
137                                 $this->currentRow = $this->resultArray['rows'][$this->currentPos];
138                                 $nextValid = true;
139                         } // END - if
140                 } // END - if
141
142                 // Return the result
143                 return $nextValid;
144         }
145
146         /**
147          * Seeks for to a specified position
148          *
149          * @param       $index  Index to seek for
150          * @return      void
151          */
152         public function seek ($index) {
153                 // Rewind to beginning
154                 $this->rewind();
155
156                 // Search for the entry
157                 while ($this->currentPos < $index && ($this->valid())) {
158                         // Continue on
159                         $this->next();
160                 } // END - while
161         }
162
163         /**
164          * Gives back the current position or null if not found
165          *
166          * @return      $current        Current element to give back
167          */
168         public function current () {
169                 // Default is not found
170                 $current = null;
171
172                 // Does the current enty exist?
173                 if (isset($this->resultArray['rows'][$this->currentPos])) {
174                         // Then get it
175                         $current = $this->resultArray['rows'][$this->currentPos];
176                 } // END - if
177
178                 // Return the result
179                 return $current;
180         }
181
182         /**
183          * Checks if next() and rewind will give a valid result
184          *
185          * @return      $isValid Wether the next/rewind entry is valid
186          */
187         public function valid () {
188                 // By default nothing is valid
189                 $isValid = false;
190
191                 // Check if 
192                 if ((isset($this->resultArray['rows'][($this->currentPos + 1)])) && (isset($this->resultArray['rows'][0]))) {
193                         // All fine!
194                         $isValid = true;
195                 } // END - if
196
197                 // Return the result
198                 return $isValid;
199         }
200
201         /**
202          * Gets the current key of iteration
203          *
204          * @return      $currentPos     Key from iterator
205          */
206         public function key () {
207                 return $this->currentPos;
208         }
209
210         /**
211          * Rewind to the beginning
212          *
213          * @return      void
214          */
215         public function rewind () {
216                 $this->currentPos = -1;
217         }
218
219         /**
220          * Searches for an entry in the data result and returns it
221          *
222          * @param       $criteriaInstance       The criteria to look inside the data set
223          * @return      $result                         Found result entry
224          */
225         public function searchEntry (LocalSearchCriteria $criteriaInstance) {
226                 die(__METHOD__.": Unfinished!");
227         }
228
229         /**
230          * Adds an update request to the database result for writing it to the
231          * database layer
232          *
233          * @param       $criteriaInstance       An instance of a updateable criteria
234          * @return      void
235          * @throws      ResultUpdateException   If no result was updated
236          */
237         public function add2UpdateQueue (LocalUpdateCriteria $criteriaInstance) {
238                 // Rewind the pointer
239                 $this->rewind();
240
241                 // Get search criteria
242                 $searchInstance = $criteriaInstance->getSearchInstance();
243
244                 // And start looking for the result
245                 $foundEntries = 0;
246                 while (($this->valid()) && ($foundEntries < $searchInstance->getLimit())) {
247                         // Get next entry
248                         $this->next();
249                         $currentEntry = $this->current();
250
251                         // Is this entry found?
252                         if ($searchInstance->ifEntryMatches($currentEntry)) {
253                                 // Update this entry
254                                 $this->updateCurrentEntryByCriteria($criteriaInstance);
255
256                                 // Count one up
257                                 $foundEntries++;
258                         } // END - if
259                 } // END - while
260
261                 // Set affected rows
262                 $this->setAffectedRows($foundEntries);
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 search instance
271                 $this->setSearchInstance($searchInstance);
272         }
273
274         /**
275          * Setter for affected rows
276          *
277          * @param       $rows   Number of affected rows
278          * @return      void
279          */
280         public final function setAffectedRows ($rows) {
281                 $this->affectedRows = $rows;
282         }
283
284         /**
285          * Getter for affected rows
286          *
287          * @return      $rows   Number of affected rows
288          */
289         public final function getAffectedRows () {
290                 return $this->affectedRows;
291         }
292
293         /**
294          * Checks wether we have out-dated entries or not
295          *
296          * @return      $needsUpdate    Wether we have out-dated entries
297          */
298         public function ifDataNeedsFlush () {
299                 $needsUpdate = (count($this->outDated) > 0);
300                 return $needsUpdate;
301         }
302
303         /**
304          * Adds registration elements to a given dataset instance
305          *
306          * @param       $criteriaInstance       An instance of a storeable criteria
307          * @return      void
308          */
309         public function addElementsToDataSet (StoreableCriteria $criteriaInstance) {
310                 // Rewind the pointer
311                 $this->rewind();
312
313                 // Walk through all entries
314                 while ($this->valid()) {
315                         // Get next entry
316                         $this->next();
317                         $currentEntry = $this->current();
318
319                         // Walk only through out-dated columns
320                         foreach ($this->outDated as $key=>$dummy) {
321                                 // Does this key exist?
322                                 //* DEBUG: */ echo "outDated: {$key}<br />\n";
323                                 if (isset($currentEntry[$key])) {
324                                         // Then update it
325                                         $criteriaInstance->addCriteria($key, $currentEntry[$key]);
326                                 } // END - foreach
327                         } // END - foreach
328                 } // END - while
329         }
330 }
331
332 // [EOF]
333 ?>