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