3 namespace CoreFramework\Result\Database;
5 // Import framework stuff
6 use CoreFramework\Criteria\Local\LocalSearchCriteria;
7 use CoreFramework\Criteria\Local\LocalUpdateCriteria;
8 use CoreFramework\Criteria\Storing\StoreableCriteria;
9 use CoreFramework\Database\Frontend\DatabaseWrapper;
10 use CoreFramework\Database\Backend\BaseDatabaseBackend;
11 use CoreFramework\Request\Requestable;
12 use CoreFramework\Result\Search\SearchableResult;
13 use CoreFramework\Result\Update\UpdateableResult;
16 use \SeekableIterator;
19 * A database result class
21 * @author Roland Haeder <webmaster@shipsimu.org>
23 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
24 * @license GNU GPL 3.0 or any newer version
25 * @link http://www.shipsimu.org
27 * This program is free software: you can redistribute it and/or modify
28 * it under the terms of the GNU General Public License as published by
29 * the Free Software Foundation, either version 3 of the License, or
30 * (at your option) any later version.
32 * This program is distributed in the hope that it will be useful,
33 * but WITHOUT ANY WARRANTY; without even the implied warranty of
34 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 * GNU General Public License for more details.
37 * You should have received a copy of the GNU General Public License
38 * along with this program. If not, see <http://www.gnu.org/licenses/>.
40 class CachedDatabaseResult extends BaseDatabaseResult implements SearchableResult, UpdateableResult, SeekableIterator {
41 // Exception constants
42 const EXCEPTION_INVALID_DATABASE_RESULT = 0x1c0;
43 const EXCEPTION_RESULT_UPDATE_FAILED = 0x1c1;
46 * Current position in array
48 private $currentPos = -1;
53 private $currentRow = NULL;
58 private $resultArray = array();
61 * Array of out-dated entries
63 private $outDated = array();
68 private $affectedRows = 0;
73 private $foundValue = '';
76 * Protected constructor
80 protected function __construct () {
81 // Call parent constructor
82 parent::__construct(__CLASS__);
86 * Creates an instance of this result by a provided result array
88 * @param $resultArray The array holding the result from query
89 * @return $resultInstance An instance of this class
91 public static final function createCachedDatabaseResult (array $resultArray) {
93 $resultInstance = new CachedDatabaseResult();
95 // Set the result array
96 $resultInstance->setResultArray($resultArray);
99 $resultInstance->setAffectedRows(count($resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS]));
101 // Return the instance
102 return $resultInstance;
106 * Setter for result array
108 * @param $resultArray The array holding the result from query
111 protected final function setResultArray (array $resultArray) {
112 $this->resultArray = $resultArray;
116 * Updates the current entry by given update criteria
118 * @param $updateInstance An instance of an Updateable criteria
121 private function updateCurrentEntryByCriteria (LocalUpdateCriteria $updateInstance) {
122 // Get the current entry key
123 $entryKey = $this->key();
125 // Now get the update criteria array and update all entries
126 foreach ($updateInstance->getUpdateCriteria() as $criteriaKey => $criteriaValue) {
128 $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$entryKey][$criteriaKey] = $criteriaValue;
130 // Mark it as out-dated
131 $this->outDated[$criteriaKey] = 1;
136 * "Iterator" method next() to advance to the next valid entry. This method
137 * does also check if result is invalid
139 * @return $nextValid Whether the next entry is valid
141 public function next () {
142 // Default is not valid
145 // Is the result valid?
146 if ($this->valid()) {
147 // Next entry found, so count one up and cache it
149 $this->currentRow = $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos];
158 * Seeks for to a specified position
160 * @param $index Index to seek for
163 public function seek ($index) {
164 // Rewind to beginning
167 // Search for the entry
168 while (($this->currentPos < $index) && ($this->valid())) {
175 * Gives back the current position or null if not found
177 * @return $current Current element to give back
179 public function current () {
180 // Default is not found
183 // Does the current enty exist?
184 if (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos])) {
186 $current = $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos];
194 * Checks if next() and rewind will give a valid result
196 * @return $isValid Whether the next/rewind entry is valid
198 public function valid () {
199 // By default nothing is valid
203 //*NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] this->currentPos=' . $this->currentPos);
205 // Check if all is fine ...
206 if (($this->ifStatusIsOkay()) && (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][($this->currentPos + 1)])) && (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][0]))) {
216 * Returns count of entries
218 * @return $isValid Whether the next/rewind entry is valid
220 public function count () {
222 return count($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS]);
226 * Determines whether the status of the query was fine (BaseDatabaseBackend::RESULT_OKAY)
228 * @return $ifStatusOkay Whether the status of the query was okay
230 public function ifStatusIsOkay () {
231 $ifStatusOkay = ((isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_STATUS])) && ($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_STATUS] === BaseDatabaseBackend::RESULT_OKAY));
232 //*NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] ifStatusOkay=' . intval($ifStatusOkay));
233 return $ifStatusOkay;
237 * Gets the current key of iteration
239 * @return $currentPos Key from iterator
241 public function key () {
242 return $this->currentPos;
246 * Rewind to the beginning and clear array $currentRow
250 public function rewind () {
251 $this->currentPos = -1;
252 $this->currentRow = array();
256 * Searches for an entry in data result and returns it
258 * @param $criteriaInstance The criteria to look inside the data set
259 * @return $result Found result entry
262 public function searchEntry (LocalSearchCriteria $criteriaInstance) {
263 $this->debugBackTrace('[' . '[' . __METHOD__ . ':' . __LINE__ . ']: Unfinished!');
267 * Adds an update request to the database result for writing it to the
270 * @param $criteriaInstance An instance of a updateable criteria
272 * @throws ResultUpdateException If no result was updated
274 public function add2UpdateQueue (LocalUpdateCriteria $criteriaInstance) {
275 // Rewind the pointer
278 // Get search criteria
279 $searchInstance = $criteriaInstance->getSearchInstance();
281 // And start looking for the result
283 while (($this->valid()) && ($foundEntries < $searchInstance->getLimit())) {
286 $currentEntry = $this->current();
288 // Is this entry found?
289 if ($searchInstance->ifEntryMatches($currentEntry)) {
291 $this->updateCurrentEntryByCriteria($criteriaInstance);
298 // If no entry is found/updated throw an exception
299 if ($foundEntries == 0) {
300 // Throw an exception here
301 throw new ResultUpdateException($this, self::EXCEPTION_RESULT_UPDATE_FAILED);
305 $this->setAffectedRows($foundEntries);
307 // Set update instance
308 $this->setUpdateInstance($criteriaInstance);
312 * Setter for affected rows
314 * @param $rows Number of affected rows
317 public final function setAffectedRows ($rows) {
318 $this->affectedRows = $rows;
322 * Getter for affected rows
324 * @return $rows Number of affected rows
326 public final function getAffectedRows () {
327 return $this->affectedRows;
331 * Getter for found value of previous found() call
333 * @return $foundValue Found value of previous found() call
335 public final function getFoundValue () {
336 return $this->foundValue;
340 * Checks whether we have out-dated entries or not
342 * @return $needsUpdate Whether we have out-dated entries
344 public function ifDataNeedsFlush () {
345 $needsUpdate = (count($this->outDated) > 0);
350 * Adds registration elements to a given dataset instance
352 * @param $criteriaInstance An instance of a StoreableCriteria class
353 * @param $requestInstance An instance of a Requestable class
356 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance = NULL) {
357 // Walk only through out-dated columns
358 foreach ($this->outDated as $key => $dummy) {
359 // Does this key exist?
360 //* DEBUG: */ echo "outDated: {$key}<br />\n";
361 if ($this->find($key)) {
363 $criteriaInstance->addCriteria($key, $this->getFoundValue());
369 * Find a key inside the result array
371 * @param $key The key we shall find
372 * @return $found Whether the key was found or not
374 public function find ($key) {
375 // By default nothing is found
378 // Rewind the pointer
381 // Walk through all entries
382 while ($this->valid()) {
383 // Advance to next entry
386 // Get the whole array
387 $currentEntry = $this->current();
389 // Is the element there?
390 if (isset($currentEntry[$key])) {
395 $this->foundValue = $currentEntry[$key];
397 // And stop searching
407 * Solver for result index value with call-back method
409 * @param $databaseColumn Database column where the index might be found
410 * @param $wrapperInstance The wrapper instance to ask for array element
411 * @para $callBack Call-back object for setting the index;
412 * 0=object instance,1=method name
414 * @todo Find a caching way without modifying the result array
416 public function solveResultIndex ($databaseColumn, DatabaseWrapper $wrapperInstance, array $callBack) {
417 // By default nothing is found
420 // Is the element in result itself found?
421 if ($this->find($databaseColumn)) {
423 $indexValue = $this->getFoundValue();
424 } elseif ($this->find($wrapperInstance->getIndexKey())) {
426 $indexValue = $this->getFoundValue();
430 call_user_func_array($callBack, array($indexValue));