3 namespace CoreFramework\Database\Result;
6 * A database result class
8 * @author Roland Haeder <webmaster@shipsimu.org>
10 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
11 * @license GNU GPL 3.0 or any newer version
12 * @link http://www.shipsimu.org
14 * This program is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27 class CachedDatabaseResult extends BaseDatabaseResult implements SearchableResult, UpdateableResult, SeekableIterator {
28 // Exception constants
29 const EXCEPTION_INVALID_DATABASE_RESULT = 0x1c0;
30 const EXCEPTION_RESULT_UPDATE_FAILED = 0x1c1;
33 * Current position in array
35 private $currentPos = -1;
40 private $currentRow = NULL;
45 private $resultArray = array();
48 * Array of out-dated entries
50 private $outDated = array();
55 private $affectedRows = 0;
60 private $foundValue = '';
63 * Protected constructor
67 protected function __construct () {
68 // Call parent constructor
69 parent::__construct(__CLASS__);
73 * Creates an instance of this result by a provided result array
75 * @param $resultArray The array holding the result from query
76 * @return $resultInstance An instance of this class
78 public static final function createCachedDatabaseResult (array $resultArray) {
80 $resultInstance = new CachedDatabaseResult();
82 // Set the result array
83 $resultInstance->setResultArray($resultArray);
86 $resultInstance->setAffectedRows(count($resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS]));
88 // Return the instance
89 return $resultInstance;
93 * Setter for result array
95 * @param $resultArray The array holding the result from query
98 protected final function setResultArray (array $resultArray) {
99 $this->resultArray = $resultArray;
103 * Updates the current entry by given update criteria
105 * @param $updateInstance An instance of an Updateable criteria
108 private function updateCurrentEntryByCriteria (LocalUpdateCriteria $updateInstance) {
109 // Get the current entry key
110 $entryKey = $this->key();
112 // Now get the update criteria array and update all entries
113 foreach ($updateInstance->getUpdateCriteria() as $criteriaKey => $criteriaValue) {
115 $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$entryKey][$criteriaKey] = $criteriaValue;
117 // Mark it as out-dated
118 $this->outDated[$criteriaKey] = 1;
123 * "Iterator" method next() to advance to the next valid entry. This method
124 * does also check if result is invalid
126 * @return $nextValid Whether the next entry is valid
128 public function next () {
129 // Default is not valid
132 // Is the result valid?
133 if ($this->valid()) {
134 // Next entry found, so count one up and cache it
136 $this->currentRow = $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos];
145 * Seeks for to a specified position
147 * @param $index Index to seek for
150 public function seek ($index) {
151 // Rewind to beginning
154 // Search for the entry
155 while (($this->currentPos < $index) && ($this->valid())) {
162 * Gives back the current position or null if not found
164 * @return $current Current element to give back
166 public function current () {
167 // Default is not found
170 // Does the current enty exist?
171 if (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos])) {
173 $current = $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos];
181 * Checks if next() and rewind will give a valid result
183 * @return $isValid Whether the next/rewind entry is valid
185 public function valid () {
186 // By default nothing is valid
190 //*NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] this->currentPos=' . $this->currentPos);
192 // Check if all is fine ...
193 if (($this->ifStatusIsOkay()) && (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][($this->currentPos + 1)])) && (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][0]))) {
203 * Returns count of entries
205 * @return $isValid Whether the next/rewind entry is valid
207 public function count () {
209 return count($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS]);
213 * Determines whether the status of the query was fine (BaseDatabaseBackend::RESULT_OKAY)
215 * @return $ifStatusOkay Whether the status of the query was okay
217 public function ifStatusIsOkay () {
218 $ifStatusOkay = ((isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_STATUS])) && ($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_STATUS] === BaseDatabaseBackend::RESULT_OKAY));
219 //*NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] ifStatusOkay=' . intval($ifStatusOkay));
220 return $ifStatusOkay;
224 * Gets the current key of iteration
226 * @return $currentPos Key from iterator
228 public function key () {
229 return $this->currentPos;
233 * Rewind to the beginning and clear array $currentRow
237 public function rewind () {
238 $this->currentPos = -1;
239 $this->currentRow = array();
243 * Searches for an entry in data result and returns it
245 * @param $criteriaInstance The criteria to look inside the data set
246 * @return $result Found result entry
249 public function searchEntry (LocalSearchCriteria $criteriaInstance) {
250 $this->debugBackTrace('[' . '[' . __METHOD__ . ':' . __LINE__ . ']: Unfinished!');
254 * Adds an update request to the database result for writing it to the
257 * @param $criteriaInstance An instance of a updateable criteria
259 * @throws ResultUpdateException If no result was updated
261 public function add2UpdateQueue (LocalUpdateCriteria $criteriaInstance) {
262 // Rewind the pointer
265 // Get search criteria
266 $searchInstance = $criteriaInstance->getSearchInstance();
268 // And start looking for the result
270 while (($this->valid()) && ($foundEntries < $searchInstance->getLimit())) {
273 $currentEntry = $this->current();
275 // Is this entry found?
276 if ($searchInstance->ifEntryMatches($currentEntry)) {
278 $this->updateCurrentEntryByCriteria($criteriaInstance);
285 // If no entry is found/updated throw an exception
286 if ($foundEntries == 0) {
287 // Throw an exception here
288 throw new ResultUpdateException($this, self::EXCEPTION_RESULT_UPDATE_FAILED);
292 $this->setAffectedRows($foundEntries);
294 // Set update instance
295 $this->setUpdateInstance($criteriaInstance);
299 * Setter for affected rows
301 * @param $rows Number of affected rows
304 public final function setAffectedRows ($rows) {
305 $this->affectedRows = $rows;
309 * Getter for affected rows
311 * @return $rows Number of affected rows
313 public final function getAffectedRows () {
314 return $this->affectedRows;
318 * Getter for found value of previous found() call
320 * @return $foundValue Found value of previous found() call
322 public final function getFoundValue () {
323 return $this->foundValue;
327 * Checks whether we have out-dated entries or not
329 * @return $needsUpdate Whether we have out-dated entries
331 public function ifDataNeedsFlush () {
332 $needsUpdate = (count($this->outDated) > 0);
337 * Adds registration elements to a given dataset instance
339 * @param $criteriaInstance An instance of a StoreableCriteria class
340 * @param $requestInstance An instance of a Requestable class
343 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance = NULL) {
344 // Walk only through out-dated columns
345 foreach ($this->outDated as $key => $dummy) {
346 // Does this key exist?
347 //* DEBUG: */ echo "outDated: {$key}<br />\n";
348 if ($this->find($key)) {
350 $criteriaInstance->addCriteria($key, $this->getFoundValue());
356 * Find a key inside the result array
358 * @param $key The key we shall find
359 * @return $found Whether the key was found or not
361 public function find ($key) {
362 // By default nothing is found
365 // Rewind the pointer
368 // Walk through all entries
369 while ($this->valid()) {
370 // Advance to next entry
373 // Get the whole array
374 $currentEntry = $this->current();
376 // Is the element there?
377 if (isset($currentEntry[$key])) {
382 $this->foundValue = $currentEntry[$key];
384 // And stop searching
394 * Solver for result index value with call-back method
396 * @param $databaseColumn Database column where the index might be found
397 * @param $wrapperInstance The wrapper instance to ask for array element
398 * @para $callBack Call-back object for setting the index;
399 * 0=object instance,1=method name
401 * @todo Find a caching way without modifying the result array
403 public function solveResultIndex ($databaseColumn, DatabaseWrapper $wrapperInstance, array $callBack) {
404 // By default nothing is found
407 // Is the element in result itself found?
408 if ($this->find($databaseColumn)) {
410 $indexValue = $this->getFoundValue();
411 } elseif ($this->find($wrapperInstance->getIndexKey())) {
413 $indexValue = $this->getFoundValue();
417 call_user_func_array($callBack, array($indexValue));