]> git.mxchange.org Git - core.git/blob - framework/main/classes/database/backend/lfdb_legacy/class_CachedLocalFileDatabase.php
Continued:
[core.git] / framework / main / classes / database / backend / lfdb_legacy / class_CachedLocalFileDatabase.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Database\Backend\Lfdb;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Criteria\Criteria;
8 use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
9 use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
10 use Org\Mxchange\CoreFramework\Database\Backend\BaseDatabaseBackend;
11 use Org\Mxchange\CoreFramework\Database\Backend\DatabaseBackend;
12 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
13 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
14 use Org\Mxchange\CoreFramework\Generic\FrameworkException;
15 use Org\Mxchange\CoreFramework\Result\Database\BaseDatabaseResult;
16 use Org\Mxchange\CoreFramework\Traits\Compressor\Channel\CompressorChannelTrait;
17 use Org\Mxchange\CoreFramework\Traits\Handler\Io\IoHandlerTrait;
18
19 // Import SPL stuff
20 use \InvalidArgumentException;
21 use \SplFileInfo;
22
23 /**
24  * Database backend class for storing objects in locally created files.
25  *
26  * This class serializes arrays stored in the dataset instance and saves them
27  * to local files. Every file (except 'info') represents a single line. Every
28  * directory within the 'db' (base) directory represents a table.
29  *
30  * A configurable 'file_io_class' is being used as "storage backend".
31  *
32  * @author              Roland Haeder <webmaster@shipsimu.org>
33  * @version             0.0.0
34  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
35  * @license             GNU GPL 3.0 or any newer version
36  * @link                http://www.shipsimu.org
37  *
38  * This program is free software: you can redistribute it and/or modify
39  * it under the terms of the GNU General Public License as published by
40  * the Free Software Foundation, either version 3 of the License, or
41  * (at your option) any later version.
42  *
43  * This program is distributed in the hope that it will be useful,
44  * but WITHOUT ANY WARRANTY; without even the implied warranty of
45  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
46  * GNU General Public License for more details.
47  *
48  * You should have received a copy of the GNU General Public License
49  * along with this program. If not, see <http://www.gnu.org/licenses/>.
50  */
51 class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBackend {
52         // Load traits
53         use CompressorChannelTrait;
54         use IoHandlerTrait;
55
56         /**
57          * The file's extension
58          */
59         private $fileExtension = 'serialized';
60
61         /**
62          * The last read file's name
63          */
64         private $lastFile = '';
65
66         /**
67          * The last read file's content including header information
68          */
69         private $lastContents = [];
70
71         /**
72          * Whether the "connection is already up
73          */
74         private $alreadyConnected = false;
75
76         /**
77          * Table information array
78          */
79         private $tableInfo = [];
80
81         /**
82          * Element for index
83          */
84         private $indexKey = '__idx';
85
86         /**
87          * The protected constructor. Do never instance from outside! You need to
88          * set a local file path. The class will then validate it.
89          *
90          * @return      void
91          */
92         protected function __construct () {
93                 // Call parent constructor
94                 parent::__construct(__CLASS__);
95         }
96
97         /**
98          * Create an object of CachedLocalFileDatabase and set the save path from
99          * configuration for local files.
100          *
101          * @return      $databaseInstance       An instance of CachedLocalFileDatabase
102          */
103         public static final function createCachedLocalFileDatabase () {
104                 // Get an instance
105                 $databaseInstance = new CachedLocalFileDatabase();
106
107                 // Set the compressor channel
108                 $databaseInstance->setCompressorChannelInstance(ObjectFactory::createObjectByConfiguredName('compressor_channel_class'));
109
110                 // Get a file IO handler and set it
111                 $databaseInstance->setFileIoInstance(ObjectFactory::createObjectByConfiguredName('file_io_class'));
112
113                 // "Connect" to the database
114                 $databaseInstance->connectToDatabase();
115
116                 // Return database instance
117                 return $databaseInstance;
118         }
119
120         /**
121          * Setter for the last read file
122          *
123          * @param       $infoInstance   The FQFN of the last read file
124          * @return      void
125          */
126         private final function setLastFile (SplFileInfo $infoInstance) {
127                 // Cast string and set it
128                 $this->lastFile = $infoInstance;
129         }
130
131         /**
132          * Getter for last read file
133          *
134          * @return      $lastFile       The last read file's name with full path
135          */
136         public final function getLastFile () {
137                 return $this->lastFile;
138         }
139
140         /**
141          * Setter for contents of the last read file
142          *
143          * @param               $contents       An array with header and data elements
144          * @return      void
145          */
146         private final function setLastFileContents (array $contents) {
147                 // Set array
148                 $this->lastContents = $contents;
149         }
150
151         /**
152          * Getter for last read file's content as an array
153          *
154          * @return      $lastContent    The array with elements 'header' and 'data'.
155          */
156         public final function getLastContents () {
157                 return $this->lastContents;
158         }
159
160         /**
161          * Getter for file extension
162          *
163          * @return      $fileExtension  The array with elements 'header' and 'data'.
164          */
165         public final function getFileExtension () {
166                 return $this->fileExtension;
167         }
168
169         /**
170          * Getter for index key
171          *
172          * @return      $indexKey       Index key
173          */
174         public final function getIndexKey () {
175                 return $this->indexKey;
176         }
177
178         /**
179          * Reads a local data file  and returns it's contents in an array
180          *
181          * @param       $infoInstance   An instance of a SplFileInfo class
182          * @return      $dataArray
183          */
184         private function getDataArrayFromFile (SplFileInfo $infoInstance) {
185                 // Init compressed data
186                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Reading elements from database file ' . $infoInstance . ' ...');
187                 $compressedData = $this->getFileIoInstance()->loadFileContents($infoInstance);
188                 $compressedData = $compressedData['data'];
189
190                 // Decompress it
191                 $serializedData = $this->getCompressorChannelInstance()->getCompressor()->decompressStream($compressedData);
192
193                 // Unserialize it
194                 $dataArray = json_decode($serializedData, true);
195
196                 // Finally return it
197                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Read ' . count($dataArray) . ' elements from database file ' . $infoInstance . '.');
198                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: dataArray=' . print_r($dataArray, true));
199                 return $dataArray;
200         }
201
202         /**
203          * Writes data array to local file
204          *
205          * @param       $infoInstance   An instance of a SplFileInfo class
206          * @param       $dataArray      An array with all the data we shall write
207          * @return      void
208          */
209         private function writeDataArrayToFqfn (SplFileInfo $infoInstance, array $dataArray) {
210                 // Serialize and compress it
211                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Flushing ' . count($dataArray) . ' elements to database file ' . $infoInstance . ' ...');
212                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: dataArray=' . print_r($dataArray, true));
213                 $compressedData = $this->getCompressorChannelInstance()->getCompressor()->compressStream(json_encode($dataArray));
214
215                 // Write this data BASE64 encoded to the file
216                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Writing ' . strlen($compressedData) . ' bytes ...');
217                 $this->getFileIoInstance()->saveStreamToFile($infoInstance, $compressedData, $this);
218
219                 // Debug message
220                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Flushing ' . count($dataArray) . ' elements to database file completed.');
221         }
222
223         /**
224          * Getter for table information file contents or an empty if info file was not created
225          *
226          * @param       $dataSetInstance        An instance of a database set class
227          * @return      $infoArray                      An array with all table informations
228          */
229         private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
230                 // Default content is no data
231                 $infoArray = [];
232
233                 // Create FQFN for getting the table information file
234                 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
235
236                 // Get the file contents
237                 try {
238                         $infoArray = $this->getDataArrayFromFile($infoInstance);
239                 } catch (FileNotFoundException $e) {
240                         // Not found, so ignore it here
241                 }
242
243                 // ... and return it
244                 return $infoArray;
245         }
246
247         /**
248          * Generates a file info class from given dataset instance and string
249          *
250          * @param       $dataSetInstance        An instance of a database set class
251          * @param       $rowName                        Name of the row
252          * @return      $infoInstance           An instance of a SplFileInfo class
253          */
254         private function generateFileFromDataSet (Criteria $dataSetInstance, string $rowName) {
255                 // Instanciate new file object
256                 $infoInstance = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR . $rowName . '.' . $this->getFileExtension());
257
258                 // Return it
259                 return $infoInstance;
260         }
261
262         /**
263          * Creates the table info file from given dataset instance
264          *
265          * @param       $dataSetInstance        An instance of a database set class
266          * @return      void
267          */
268         private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
269                 // Create FQFN for creating the table information file
270                 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
271
272                 // Get the data out from dataset in a local array
273                 $this->tableInfo[$dataSetInstance->getTableName()] = array(
274                         'primary'      => $dataSetInstance->getPrimaryKey(),
275                         'created'      => time(),
276                         'last_updated' => time()
277                 );
278
279                 // Write the data to the file
280                 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$dataSetInstance->getTableName()]);
281         }
282
283         /**
284          * Updates the table info file from given dataset instance
285          *
286          * @param       $dataSetInstance        An instance of a database set class
287          * @return      void
288          */
289         private function updateTableInfoFile (StoreableCriteria $dataSetInstance) {
290                 // Get table name from criteria
291                 $tableName = $dataSetInstance->getTableName();
292
293                 // Create FQFN for creating the table information file
294                 $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
295
296                 // Get the data out from dataset in a local array
297                 $this->tableInfo[$tableName]['primary']      = $dataSetInstance->getPrimaryKey();
298                 $this->tableInfo[$tableName]['last_updated'] = time();
299
300                 // Write the data to the file
301                 $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$tableName]);
302         }
303
304         /**
305          * Updates the primary key information or creates the table info file if not found
306          *
307          * @param       $dataSetInstance        An instance of a database set class
308          * @return      void
309          */
310         private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
311                 // Get table name from criteria
312                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
313                 $tableName = $dataSetInstance->getTableName();
314
315                 // Get the information array from lower method
316                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: tableName=%s', $tableName));
317                 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
318
319                 // Is the primary key there?
320                 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableInfo=' . print_r($this->tableInfo, true));
321                 if (!isset($this->tableInfo[$tableName]['primary'])) {
322                         // Then create the info file
323                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Creating info table for tableName=%s ...', $tableName));
324                         $this->createTableInfoFile($dataSetInstance);
325                 } elseif ((FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo[$tableName]['primary'])) {
326                         // Set the array element
327                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Setting primaryKey=%s for tableName=%s ...', $dataSetInstance->getPrimaryKey(), $tableName));
328                         $this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
329
330                         // Update the entry
331                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Updating info table for tableName=%s ...', $tableName));
332                         $this->updateTableInfoFile($dataSetInstance);
333                 }
334
335                 // Trace message
336                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: EXIT!');
337         }
338
339         /**
340          * Makes sure that the database connection is alive
341          *
342          * @return      void
343          * @todo        Do some checks on the database directory and files here
344          */
345         public function connectToDatabase () {
346         }
347
348         /**
349          * Starts a SELECT query on the database by given return type, table name
350          * and search criteria
351          *
352          * @param       $tableName                      Name of the database table
353          * @param       $searchInstance         Local search criteria class
354          * @return      $resultData                     Result data of the query
355          * @throws      InvalidArgumentException        If a parameter is not valid
356          * @throws      UnsupportedCriteriaException    If the criteria is unsupported
357          * @throws      SqlException                                    If an 'SQL error' occurs
358          */
359         public function querySelect (string $tableName, LocalSearchCriteria $searchInstance) {
360                 // Validate parameter
361                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: tableName=%s,searchInstance=%s - CALLED!', $tableName, $searchInstance->__toString()));
362                 if (empty($tableName)) {
363                         // Throw IAE
364                         throw new InvalidArgumentException('Parameter "tableName" is empty');
365                 }
366
367                 // The result is null by any errors
368                 $resultData = NULL;
369
370                 // Create full path name
371                 $pathName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
372
373                 /*
374                  * A 'select' query is not that easy on local files, so first try to
375                  * find the 'table' which is in fact a directory on the server
376                  */
377                 try {
378                         // Get a directory pointer instance
379                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Getting directory_class for pathName=%s ...', $pathName));
380                         $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
381
382                         // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
383                         $resultData = [
384                                 BaseDatabaseResult::RESULT_NAME_STATUS => self::RESULT_OKAY,
385                                 BaseDatabaseResult::RESULT_NAME_ROWS   => []
386                         ];
387
388                         // Initialize limit/skip
389                         $limitFound = 0;
390                         $skipFound = 0;
391                         $idx = 1;
392
393                         // Read the directory with some exceptions
394                         while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
395                                 // Does the extension match?
396                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: fileInfoInstance->extension=%s,this->fileExtension=%s', $fileInfoInstance->getExtension(), $this->getFileExtension()));
397                                 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
398                                         // Skip this file!
399                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Skipping fileInfoInstance->filename=%s ...', $fileInfoInstance->getFilename()));
400                                         $directoryInstance->getDirectoryIteratorInstance()->next();
401                                         continue;
402                                 }
403
404                                 // Read the file
405                                 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
406
407                                 // Is this an array?
408                                 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
409                                 if (is_array($dataArray)) {
410                                         // Default is nothing found
411                                         $isFound = true;
412
413                                         // Search in the criteria with FMFW (First Matches, First Wins)
414                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: data[]=%d', count($dataArray)));
415                                         foreach ($dataArray as $key => $value) {
416                                                 // Make sure value is not bool
417                                                 assert(!is_bool($value));
418
419                                                 // Found one entry?
420                                                 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
421                                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: key=%s,value[%s]=%s,isFound=%s', $key, gettype($value), $value, intval($isFound)));
422                                         }
423
424                                         // Is all found?
425                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: isFound=%d,limitFound=%d,limit=%d', intval($isFound), $limitFound, $searchInstance->getLimit()));
426                                         if ($isFound === true) {
427                                                 // Shall we skip this entry?
428                                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: searchInstance->skip=%d', $searchInstance->getSkip()));
429                                                 if ($searchInstance->getSkip() > 0) {
430                                                         // We shall skip some entries
431                                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: skipFound=%s', $skipFound));
432                                                         if ($skipFound < $searchInstance->getSkip()) {
433                                                                 // Skip this entry
434                                                                 $skipFound++;
435                                                                 break;
436                                                         }
437                                                 }
438
439                                                 // Set id number
440                                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: Setting dataArray[%s]=%d', $this->getIndexKey(), $idx));
441                                                 $dataArray[$this->getIndexKey()] = $idx;
442
443                                                 // Entry found!
444                                                 array_push($resultData[BaseDatabaseResult::RESULT_NAME_ROWS], $dataArray);
445
446                                                 // Count found entries up
447                                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: resultData[%s]()=%d', BaseDatabaseResult::RESULT_NAME_ROWS, count($resultData[BaseDatabaseResult::RESULT_NAME_ROWS])));
448                                                 $limitFound++;
449                                         }
450                                 } else {
451                                         // Throw an exception here
452                                         throw new SqlException(array($this, sprintf('File &#39;%s&#39; contains invalid data.', $fileInfoInstance->getPathname()), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
453                                 }
454
455                                 // Count entry up
456                                 $idx++;
457
458                                 // Advance to next entry
459                                 $directoryInstance->getDirectoryIteratorInstance()->next();
460                         }
461
462                         // Close directory and throw the instance away
463                         $directoryInstance->closeDirectory();
464                         unset($directoryInstance);
465
466                         // Reset last exception
467                         $this->resetLastException();
468                 } catch (PathIsNoDirectoryException $e) {
469                         // Path not found means "table not found" for real databases...
470                         $this->setLastException($e);
471
472                         // So throw an SqlException here with faked error message
473                         throw new SqlException (array($this, sprintf('Table &#39;%s&#39; not found', $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
474                 } catch (FrameworkException $e) {
475                         // Catch all exceptions and store them in last error
476                         $this->setLastException($e);
477                 }
478
479                 // Return the gathered result
480                 return $resultData;
481         }
482
483         /**
484          * "Inserts" a data set instance into a local file database folder
485          *
486          * @param       $dataSetInstance        A storeable data set
487          * @return      void
488          * @throws      SqlException    If an SQL error occurs
489          */
490         public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
491                 // Try to save the request away
492                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LFDB: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
493                 try {
494                         // Create full path name
495                         $infoInstance = $this->generateFileFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
496
497                         // Write the data away
498                         $this->writeDataArrayToFqfn($infoInstance, $dataSetInstance->getCriteriaArray());
499
500                         // Update the primary key
501                         $this->updatePrimaryKey($dataSetInstance);
502
503                         // Reset last exception
504                         $this->resetLastException();
505                 } catch (FrameworkException $e) {
506                         // Catch all exceptions and store them in last error
507                         $this->setLastException($e);
508
509                         // Throw an SQL exception
510                         throw new SqlException(array(
511                                         $this,
512                                         sprintf('Cannot write data to table &#39;%s&#39;, is the table created?', $dataSetInstance->getTableName()),
513                                         self::DB_CODE_TABLE_UNWRITEABLE
514                                 ),
515                                 self::EXCEPTION_SQL_QUERY
516                         );
517                 }
518
519                 // Trace message
520                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: EXIT!');
521         }
522
523         /**
524          * "Updates" a data set instance with a database layer
525          *
526          * @param       $dataSetInstance        An instance of a StorableCriteria class
527          * @return      void
528          * @throws      SqlException    If an SQL error occurs
529          */
530         public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
531                 // Create full path name
532                 $pathName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR;
533
534                 // Try all the requests
535                 try {
536                         // Get a file pointer instance
537                         $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
538
539                         // Initialize limit/skip
540                         $limitFound = 0;
541                         $skipFound = 0;
542
543                         // Get the criteria array from the dataset
544                         $searchArray = $dataSetInstance->getCriteriaArray();
545
546                         // Get search criteria
547                         $searchInstance = $dataSetInstance->getSearchInstance();
548
549                         // Read the directory with some exceptions
550                         while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
551                                 // Does the extension match?
552                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
553                                 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
554                                         // Skip this file!
555                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
556                                         $directoryInstance->getDirectoryIteratorInstance()->next();
557                                         continue;
558                                 }
559
560                                 // Open this file for reading
561                                 $dataArray = $this->getDataArrayFromFile($fileInfoInstance);
562                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
563
564                                 // Is this an array?
565                                 if (is_array($dataArray)) {
566                                         // Default is nothing found
567                                         $isFound = true;
568
569                                         // Search in the criteria with FMFW (First Matches, First Wins)
570                                         foreach ($dataArray as $key => $value) {
571                                                 // Make sure value is not bool
572                                                 assert(!is_bool($value));
573
574                                                 // Found one entry?
575                                                 $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
576                                         }
577
578                                         // Is all found?
579                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: isFound=' . intval($isFound));
580                                         if ($isFound === true) {
581                                                 // Shall we skip this entry?
582                                                 if ($searchInstance->getSkip() > 0) {
583                                                         // We shall skip some entries
584                                                         if ($skipFound < $searchInstance->getSkip()) {
585                                                                 // Skip this entry
586                                                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Found entry, but skipping ...');
587                                                                 $skipFound++;
588                                                                 break;
589                                                         }
590                                                 }
591
592                                                 // Entry found, so update it
593                                                 foreach ($searchArray as $searchKey => $searchValue) {
594                                                         // Make sure the value is not bool again
595                                                         assert(!is_bool($searchValue));
596                                                         assert($searchKey != $this->indexKey);
597
598                                                         // Debug message + add/update it
599                                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: criteriaKey=' . $searchKey . ',criteriaValue=' . $searchValue);
600                                                         $dataArray[$searchKey] = $searchValue;
601                                                 }
602
603                                                 // Write the data to a local file
604                                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: Writing data[]=' . count($dataArray) . ' to ' . $fileInfoInstance->getPathname() . ' ...');
605                                                 $this->writeDataArrayToFqfn($fileInfoInstance, $dataArray);
606
607                                                 // Count found entries up
608                                                 $limitFound++;
609                                         }
610                                 }
611
612                                 // Advance to next entry
613                                 $directoryInstance->getDirectoryIteratorInstance()->next();
614                         }
615
616                         // Close the file pointer
617                         $directoryInstance->closeDirectory();
618
619                         // Update the primary key
620                         $this->updatePrimaryKey($dataSetInstance);
621
622                         // Reset last exception
623                         $this->resetLastException();
624                 } catch (FrameworkException $e) {
625                         // Catch all exceptions and store them in last error
626                         $this->setLastException($e);
627
628                         // Throw an SQL exception
629                         throw new SqlException(array($this, sprintf('Cannot write data to table &#39;%s&#39;, is the table created? Exception: %s, message:%s', $dataSetInstance->getTableName(), $e->__toString(), $e->getMessage()), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
630                 }
631         }
632
633         /**
634          * Getter for primary key of specified table or if not found null will be
635          * returned. This must be database-specific.
636          *
637          * @param       $tableName              Name of the table we need the primary key from
638          * @return      $primaryKey             Primary key column of the given table
639          * @throws      InvalidArgumentException        If a parameter is not valid
640          * @todo        Rename method to getPrimaryKeyFromTableInfo()
641          */
642         public function getPrimaryKeyOfTable (string $tableName) {
643                 // Validate parameter
644                 if (empty($tableName)) {
645                         // Throw IAE
646                         throw new InvalidArgumentException('Parameter "tableName" is empty');
647                 }
648
649                 // Default key is null
650                 $primaryKey = NULL;
651
652                 // Does the table information exist?
653                 if (isset($this->tableInfo[$tableName])) {
654                         // Then return the primary key
655                         $primaryKey = $this->tableInfo[$tableName]['primary'];
656                 }
657
658                 // Return the column
659                 return $primaryKey;
660         }
661
662         /**
663          * Removes non-public data from given array.
664          *
665          * @param       $data   An array with possible non-public data that needs to be removed.
666          * @return      $data   A cleaned up array with only public data.
667          * @todo        Add more generic non-public data for removal
668          */
669         public function removeNonPublicDataFromArray (array $data) {
670                 // Remove '__idx'
671                 unset($data[$this->indexKey]);
672
673                 // Return it
674                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: data[' . gettype($data) . ']='.print_r($data, true));
675                 return $data;
676         }
677
678         /**
679          * Counts total rows of given table
680          *
681          * @param       $tableName      Table name
682          * @return      $count          Total rows of given table
683          * @throws      InvalidArgumentException        If a parameter is not valid
684          */
685         public function countTotalRows (string $tableName) {
686                 // Validate parameter
687                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableName=' . $tableName . ' - CALLED!');
688                 if (empty($tableName)) {
689                         // Throw IAE
690                         throw new InvalidArgumentException('Parameter "tableName" is empty');
691                 }
692
693
694                 // Create full path name
695                 $pathName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
696
697                 // Try all the requests
698                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: pathName=' . $pathName);
699                 try {
700                         // Get a file pointer instance
701                         $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
702
703                         // Initialize counter
704                         $count = 0;
705
706                         // Read the directory with some exceptions
707                         while ($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) {
708                                 // Does the extension match?
709                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
710                                 if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
711                                         // Debug message
712                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
713                                         // Skip this file!
714                                         continue;
715                                 }
716
717                                 // Count this row up
718                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',getFileExtension()=' . $this->getFileExtension() . ' - COUNTED!');
719                                 $count++;
720                         }
721                 } catch (FrameworkException $e) {
722                         // Catch all exceptions and store them in last error
723                         $this->setLastException($e);
724
725                         // Throw an SQL exception
726                         throw new SqlException(array($this, sprintf('Cannot count on table &#39;%s&#39;, is the table created?', $dataSetInstance->getTableName()), self::DB_CODE_TABLE_NOT_FOUND), self::EXCEPTION_SQL_QUERY);
727                 }
728
729                 // Return count
730                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LFDB: tableName=' . $tableName . ',count=' . $count . ' - EXIT!');
731                 return $count;
732         }
733
734 }