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\DatabaseFrontend;
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 \InvalidArgumentException;
16 use \SeekableIterator;
19 * A database result class
21 * @author Roland Haeder <webmaster@shipsimu.org>
23 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 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 = [];
61 * Array of out-dated entries
63 private $outDated = [];
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
90 * @throws InvalidArgumentException If a parameter is invalid
92 public static final function createCachedDatabaseResult (array $resultArray) {
94 if (count($resultArray) == 0) {
96 throw new InvalidArgumentException('Array "resultArray" cannot be empty.');
97 } elseif (!array_key_exists(BaseDatabaseBackend::RESULT_INDEX_ROWS, $resultArray)) {
98 // Yes, then abort here
99 throw new InvalidArgumentException(sprintf('resultArray(%d)=%s has no element "%s".', count($resultArray), print_r($resultArray, TRUE), BaseDatabaseBackend::RESULT_INDEX_ROWS));
102 // Get a new instance
103 $resultInstance = new CachedDatabaseResult();
105 // Set the result array and reset current position
106 $resultInstance->setResultArray($resultArray);
107 $resultInstance->resetCurrentPosition();
110 $resultInstance->setAffectedRows(count($resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS]));
112 // Return the instance
113 return $resultInstance;
117 * Setter for result array
119 * @param $resultArray The array holding the result from query
122 protected final function setResultArray (array $resultArray) {
123 $this->resultArray = $resultArray;
127 * Updates the current entry by given update criteria
129 * @param $updateInstance An instance of an Updateable criteria
132 private function updateCurrentEntryByCriteria (LocalUpdateCriteria $updateInstance) {
133 // Get the current entry key
134 $entryKey = $this->key();
136 // Now get the update criteria array and update all entries
137 foreach ($updateInstance->getUpdateCriteria() as $criteriaKey => $criteriaValue) {
139 $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$entryKey][$criteriaKey] = $criteriaValue;
141 // Mark it as out-dated
142 $this->outDated[$criteriaKey] = 1;
147 * "Iterator" method next() to advance to the next valid entry. This method
148 * does also check if result is invalid
150 * @return $nextValid Whether the next entry is valid
152 public function next () {
153 // Default is not valid
156 // Is the result valid?
157 if ($this->valid()) {
158 // Next entry found, so count one up and cache it
160 $this->currentRow = $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos];
169 * Seeks for to a specified position
171 * @param $index Index to seek for
174 public function seek ($index) {
175 // Rewind to beginning
178 // Search for the entry
179 while (($this->currentPos < $index) && ($this->valid())) {
186 * Gives back the current position or null if not found
188 * @return $current Current element to give back
190 public function current () {
191 // Default is not found
194 // Does the current enty exist?
195 if (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos])) {
197 $current = $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos];
205 * Checks if next() and rewind will give a valid result
207 * @return $isValid Whether the next/rewind entry is valid
209 public function valid () {
210 // Check if all is fine ...
211 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-DATABASE-RESULT: this->currentPos=%d - CALLED!', $this->currentPos));
212 $isValid = ($this->ifStatusIsOkay() && isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos]) && isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][0]));
215 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-DATABASE-RESULT: isValid=%d - EXIT!', intval($isValid)));
220 * Returns count of entries
222 * @return $isValid Whether the next/rewind entry is valid
224 public function count () {
226 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-DATABASE-RESULT: CALLED!');
227 $count = count($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS]);
230 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-DATABASE-RESULT: count=%d - EXIT!', $count));
235 * Determines whether the status of the query was fine (BaseDatabaseBackend::RESULT_OKAY)
237 * @return $ifStatusOkay Whether the status of the query was okay
239 public function ifStatusIsOkay () {
240 // Check all conditions
241 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-DATABASE-RESULT: this->currentPos=%d - CALLED!', $this->currentPos));
242 $ifStatusOkay = (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_STATUS]) && $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_STATUS] === BaseDatabaseBackend::RESULT_OKAY);
245 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-DATABASE-RESULT: ifStatusOkay=%s - EXIT!', intval($ifStatusOkay)));
246 return $ifStatusOkay;
250 * Gets the current key of iteration
252 * @return $currentPos Key from iterator
254 public function key () {
255 // Return current array position
256 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-DATABASE-RESULT: this->currentPos=%d - CALLED!', $this->currentPos));
257 return $this->currentPos;
261 * Rewind to the beginning and clear array $currentRow
265 public function rewind () {
266 // Reset both current array position and current row
267 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-DATABASE-RESULT: this->currentPos=%d - CALLED!', $this->currentPos));
268 $this->resetCurrentPosition();
269 $this->currentRow = [];
272 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-DATABASE-RESULT: EXIT!');
276 * Resets current array position to 0 if at least one record is there or -1
277 * if no record is there.
281 private function resetCurrentPosition () {
283 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-DATABASE-RESULT: CALLED!');
284 $this->currentPos = ($this->count() > 0 ? 0 : -1);
287 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-DATABASE-RESULT: EXIT!');
291 * Searches for an entry in data result and returns it
293 * @param $criteriaInstance The criteria to look inside the data set
294 * @return $result Found result entry
297 public function searchEntry (LocalSearchCriteria $criteriaInstance) {
299 $this->debugBackTrace(sprintf('[%s:%d]: criteriaInstance=%s', __METHOD__, __LINE__, print_r($criteriaInstance, TRUE)));
303 * Adds an update request to the database result for writing it to the
306 * @param $updateInstance An instance of a updateable criteria
308 * @throws ResultUpdateException If no result was updated
310 public function add2UpdateQueue (LocalUpdateCriteria $updateInstance) {
311 // Rewind the pointer
314 // Get search criteria
315 $searchInstance = $updateInstance->getSearchInstance();
317 // And start looking for the result
318 $foundEntries = $this->getAffectedRows();
319 while (($this->valid()) && ($foundEntries < $searchInstance->getLimit())) {
322 $currentEntry = $this->current();
324 // Is this entry found?
325 if ($searchInstance->ifEntryMatches($currentEntry)) {
327 $this->updateCurrentEntryByCriteria($updateInstance);
334 // If no entry is found/updated throw an exception
335 if ($foundEntries == 0) {
336 // Throw an exception here
337 throw new ResultUpdateException($this, self::EXCEPTION_RESULT_UPDATE_FAILED);
341 $this->setAffectedRows($foundEntries);
343 // Set update instance
344 $this->setUpdateInstance($updateInstance);
348 * Setter for affected rows
350 * @param $rows Number of affected rows
353 public final function setAffectedRows (int $rows) {
354 $this->affectedRows = $rows;
358 * Getter for affected rows
360 * @return $rows Number of affected rows
362 public final function getAffectedRows () {
363 return $this->affectedRows;
367 * Getter for found value of previous found() call
369 * @return $foundValue Found value of previous found() call
371 public final function getFoundValue () {
372 return $this->foundValue;
376 * Checks whether we have out-dated entries or not
378 * @return $needsUpdate Whether we have out-dated entries
380 public function ifDataNeedsFlush () {
381 $needsUpdate = (count($this->outDated) > 0);
386 * Adds registration elements to a given dataset instance
388 * @param $criteriaInstance An instance of a StoreableCriteria class
391 public function addElementsToDataSet (StoreableCriteria $criteriaInstance) {
392 // Walk only through out-dated columns
393 foreach ($this->outDated as $key => $dummy) {
394 // Does this key exist?
395 if ($this->find($key)) {
397 $criteriaInstance->addCriteria($key, $this->getFoundValue());
403 * Find a key inside the result array
405 * @param $key The key we shall find
406 * @return $found Whether the key was found or not
408 public function find (string $key) {
409 // By default nothing is found
412 // Rewind the pointer
415 // Walk through all entries
416 while ($this->valid()) {
417 // Advance to next entry
420 // Get the whole array
421 $currentEntry = $this->current();
423 // Is the element there?
424 if (isset($currentEntry[$key])) {
429 $this->foundValue = $currentEntry[$key];
431 // And stop searching
441 * Solver for result index value with call-back method
443 * @param $databaseColumn Database column where the index might be found
444 * @param $frontendInstance The frontend instance to ask for array element
445 * @para $callBack Call-back object for setting the index;
446 * 0=object instance,1=method name
448 * @todo Find a caching way without modifying the result array
450 public function solveResultIndex (string $databaseColumn, DatabaseFrontend $frontendInstance, array $callBack) {
451 // By default nothing is found
454 // Is the element in result itself found?
455 if ($this->find($databaseColumn)) {
457 $indexValue = $this->getFoundValue();
458 } elseif ($this->find($frontendInstance->getIndexKey())) {
460 $indexValue = $this->getFoundValue();
464 call_user_func_array($callBack, array($indexValue));