3 namespace Org\Mxchange\CoreFramework\Result\Database;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
7 use Org\Mxchange\CoreFramework\Criteria\Local\LocalUpdateCriteria;
8 use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
9 use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
10 use Org\Mxchange\CoreFramework\Database\Backend\BaseDatabaseBackend;
11 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
12 use Org\Mxchange\CoreFramework\Result\Update\UpdateableResult;
15 use \SeekableIterator;
18 * A database result class
20 * @author Roland Haeder <webmaster@shipsimu.org>
22 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
23 * @license GNU GPL 3.0 or any newer version
24 * @link http://www.shipsimu.org
26 * This program is free software: you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as published by
28 * the Free Software Foundation, either version 3 of the License, or
29 * (at your option) any later version.
31 * This program is distributed in the hope that it will be useful,
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
36 * You should have received a copy of the GNU General Public License
37 * along with this program. If not, see <http://www.gnu.org/licenses/>.
39 class CachedDatabaseResult extends BaseDatabaseResult implements SearchableResult, UpdateableResult, SeekableIterator {
40 // Exception constants
41 const EXCEPTION_INVALID_DATABASE_RESULT = 0x1c0;
42 const EXCEPTION_RESULT_UPDATE_FAILED = 0x1c1;
45 * Current position in array
47 private $currentPos = -1;
52 private $currentRow = NULL;
57 private $resultArray = array();
60 * Array of out-dated entries
62 private $outDated = array();
67 private $affectedRows = 0;
72 private $foundValue = '';
75 * Protected constructor
79 protected function __construct () {
80 // Call parent constructor
81 parent::__construct(__CLASS__);
85 * Creates an instance of this result by a provided result array
87 * @param $resultArray The array holding the result from query
88 * @return $resultInstance An instance of this class
90 public static final function createCachedDatabaseResult (array $resultArray) {
92 $resultInstance = new CachedDatabaseResult();
94 // Set the result array
95 $resultInstance->setResultArray($resultArray);
98 $resultInstance->setAffectedRows(count($resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS]));
100 // Return the instance
101 return $resultInstance;
105 * Setter for result array
107 * @param $resultArray The array holding the result from query
110 protected final function setResultArray (array $resultArray) {
111 $this->resultArray = $resultArray;
115 * Updates the current entry by given update criteria
117 * @param $updateInstance An instance of an Updateable criteria
120 private function updateCurrentEntryByCriteria (LocalUpdateCriteria $updateInstance) {
121 // Get the current entry key
122 $entryKey = $this->key();
124 // Now get the update criteria array and update all entries
125 foreach ($updateInstance->getUpdateCriteria() as $criteriaKey => $criteriaValue) {
127 $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$entryKey][$criteriaKey] = $criteriaValue;
129 // Mark it as out-dated
130 $this->outDated[$criteriaKey] = 1;
135 * "Iterator" method next() to advance to the next valid entry. This method
136 * does also check if result is invalid
138 * @return $nextValid Whether the next entry is valid
140 public function next () {
141 // Default is not valid
144 // Is the result valid?
145 if ($this->valid()) {
146 // Next entry found, so count one up and cache it
148 $this->currentRow = $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos];
157 * Seeks for to a specified position
159 * @param $index Index to seek for
162 public function seek ($index) {
163 // Rewind to beginning
166 // Search for the entry
167 while (($this->currentPos < $index) && ($this->valid())) {
174 * Gives back the current position or null if not found
176 * @return $current Current element to give back
178 public function current () {
179 // Default is not found
182 // Does the current enty exist?
183 if (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos])) {
185 $current = $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos];
193 * Checks if next() and rewind will give a valid result
195 * @return $isValid Whether the next/rewind entry is valid
197 public function valid () {
198 // By default nothing is valid
202 //*NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] this->currentPos=' . $this->currentPos);
204 // Check if all is fine ...
205 if (($this->ifStatusIsOkay()) && (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][($this->currentPos + 1)])) && (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][0]))) {
215 * Returns count of entries
217 * @return $isValid Whether the next/rewind entry is valid
219 public function count () {
221 return count($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS]);
225 * Determines whether the status of the query was fine (BaseDatabaseBackend::RESULT_OKAY)
227 * @return $ifStatusOkay Whether the status of the query was okay
229 public function ifStatusIsOkay () {
230 $ifStatusOkay = ((isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_STATUS])) && ($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_STATUS] === BaseDatabaseBackend::RESULT_OKAY));
231 //*NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] ifStatusOkay=' . intval($ifStatusOkay));
232 return $ifStatusOkay;
236 * Gets the current key of iteration
238 * @return $currentPos Key from iterator
240 public function key () {
241 return $this->currentPos;
245 * Rewind to the beginning and clear array $currentRow
249 public function rewind () {
250 $this->currentPos = -1;
251 $this->currentRow = array();
255 * Searches for an entry in data result and returns it
257 * @param $criteriaInstance The criteria to look inside the data set
258 * @return $result Found result entry
261 public function searchEntry (LocalSearchCriteria $criteriaInstance) {
262 $this->debugBackTrace('[' . '[' . __METHOD__ . ':' . __LINE__ . ']: Unfinished!');
266 * Adds an update request to the database result for writing it to the
269 * @param $criteriaInstance An instance of a updateable criteria
271 * @throws ResultUpdateException If no result was updated
273 public function add2UpdateQueue (LocalUpdateCriteria $criteriaInstance) {
274 // Rewind the pointer
277 // Get search criteria
278 $searchInstance = $criteriaInstance->getSearchInstance();
280 // And start looking for the result
282 while (($this->valid()) && ($foundEntries < $searchInstance->getLimit())) {
285 $currentEntry = $this->current();
287 // Is this entry found?
288 if ($searchInstance->ifEntryMatches($currentEntry)) {
290 $this->updateCurrentEntryByCriteria($criteriaInstance);
297 // If no entry is found/updated throw an exception
298 if ($foundEntries == 0) {
299 // Throw an exception here
300 throw new ResultUpdateException($this, self::EXCEPTION_RESULT_UPDATE_FAILED);
304 $this->setAffectedRows($foundEntries);
306 // Set update instance
307 $this->setUpdateInstance($criteriaInstance);
311 * Setter for affected rows
313 * @param $rows Number of affected rows
316 public final function setAffectedRows ($rows) {
317 $this->affectedRows = $rows;
321 * Getter for affected rows
323 * @return $rows Number of affected rows
325 public final function getAffectedRows () {
326 return $this->affectedRows;
330 * Getter for found value of previous found() call
332 * @return $foundValue Found value of previous found() call
334 public final function getFoundValue () {
335 return $this->foundValue;
339 * Checks whether we have out-dated entries or not
341 * @return $needsUpdate Whether we have out-dated entries
343 public function ifDataNeedsFlush () {
344 $needsUpdate = (count($this->outDated) > 0);
349 * Adds registration elements to a given dataset instance
351 * @param $criteriaInstance An instance of a StoreableCriteria class
354 public function addElementsToDataSet (StoreableCriteria $criteriaInstance) {
355 // Walk only through out-dated columns
356 foreach ($this->outDated as $key => $dummy) {
357 // Does this key exist?
358 //* DEBUG: */ echo "outDated: {$key}<br />\n";
359 if ($this->find($key)) {
361 $criteriaInstance->addCriteria($key, $this->getFoundValue());
367 * Find a key inside the result array
369 * @param $key The key we shall find
370 * @return $found Whether the key was found or not
372 public function find ($key) {
373 // By default nothing is found
376 // Rewind the pointer
379 // Walk through all entries
380 while ($this->valid()) {
381 // Advance to next entry
384 // Get the whole array
385 $currentEntry = $this->current();
387 // Is the element there?
388 if (isset($currentEntry[$key])) {
393 $this->foundValue = $currentEntry[$key];
395 // And stop searching
405 * Solver for result index value with call-back method
407 * @param $databaseColumn Database column where the index might be found
408 * @param $wrapperInstance The wrapper instance to ask for array element
409 * @para $callBack Call-back object for setting the index;
410 * 0=object instance,1=method name
412 * @todo Find a caching way without modifying the result array
414 public function solveResultIndex ($databaseColumn, DatabaseWrapper $wrapperInstance, array $callBack) {
415 // By default nothing is found
418 // Is the element in result itself found?
419 if ($this->find($databaseColumn)) {
421 $indexValue = $this->getFoundValue();
422 } elseif ($this->find($wrapperInstance->getIndexKey())) {
424 $indexValue = $this->getFoundValue();
428 call_user_func_array($callBack, array($indexValue));