3 * Database backend class for storing objects in locally created files.
5 * This class serializes objects and saves them to local files.
7 * @author Roland Haeder <webmaster@ship-simu.org>
9 * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
10 * @license GNU GPL 3.0 or any newer version
11 * @link http://www.ship-simu.org
13 * This program is free software: you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation, either version 3 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 class LocalFileDatabase extends BaseDatabaseFrontend implements DatabaseFrontendInterface {
27 // Constants for MySQL backward-compatiblity (PLEASE FIX THEM!)
28 const DB_CODE_TABLE_MISSING = 0x000;
31 * Save path for "file database"
33 private $savePath = "";
36 * The file's extension
38 private $fileExtension = "serialized";
41 * The last read file's name
43 private $lastFile = "";
46 * The last read file's content including header information
48 private $lastContents = array();
51 * Wether the "connection is already up
53 private $alreadyConnected = false;
58 private $lastError = "";
63 private $lastException = null;
66 * The protected constructor. Do never instance from outside! You need to
67 * set a local file path. The class will then validate it.
71 protected function __construct() {
72 // Call parent constructor
73 parent::__construct(__CLASS__);
76 $this->setObjectDescription("Class for local file databases");
79 $this->createUniqueID();
82 $this->removeSystemArray();
86 * Create an object of LocalFileDatabase and set the save path for local files.
87 * This method also validates the given file path.
89 * @param $savePath The local file path string
90 * @param $ioInstance The input/output handler. This
91 * should be FileIoHandler
92 * @return $dbInstance An instance of LocalFileDatabase
94 public final static function createLocalFileDatabase ($savePath, FileIoHandler $ioInstance) {
96 $dbInstance = new LocalFileDatabase();
98 // Set save path and IO instance
99 $dbInstance->setSavePath($savePath);
100 $dbInstance->setFileIoInstance($ioInstance);
102 // "Connect" to the database
103 $dbInstance->connectToDatabase();
105 // Return database instance
110 * Setter for save path
112 * @param $savePath The local save path where we shall put our serialized classes
115 public final function setSavePath ($savePath) {
117 $savePath = (string) $savePath;
120 $this->savePath = $savePath;
124 * Getter for save path
126 * @return $savePath The local save path where we shall put our serialized classes
128 public final function getSavePath () {
129 return $this->savePath;
133 * Getter for last error message
135 * @return $lastError Last error message
137 public final function getLastError () {
138 return $this->lastError;
142 * Getter for last exception
144 * @return $lastException Last thrown exception
146 public final function getLastException () {
147 return $this->lastException;
151 * Saves a given object to the local file system by serializing and
152 * transparently compressing it
154 * @param $object The object we shall save to the local file system
157 public final function saveObject (FrameworkInterface $object) {
158 // Get a string containing the serialized object. We cannot exchange
159 // $this and $object here because $object does not need to worry
160 // about it's limitations... ;-)
161 $serialized = $this->serializeObject($object);
163 // Get a path name plus file name and append the extension
164 $fqfn = $this->getSavePath() . $object->getPathFileNameFromObject() . "." . $this->getFileExtension();
166 // Save the file to disc we don't care here if the path is there,
167 // this must be done in later methods.
168 $this->getFileIoInstance()->saveFile($fqfn, array($this->getCompressorChannel()->getCompressorExtension(), $serialized));
172 * Get a serialized string from the given object
174 * @param $object The object we want to serialize and transparently
176 * @return $serialized A string containing the serialzed/compressed object
177 * @see ObjectLimits An object holding limition information
178 * @see SerializationContainer A special container class for e.g.
179 * attributes from limited objects
181 private function serializeObject (FrameworkInterface $object) {
182 // If there is no limiter instance we serialize the whole object
183 // otherwise only in the limiter object (ObjectLimits) specified
184 // attributes summarized in a special container class
185 if ($this->getLimitInstance() === null) {
186 // Serialize the whole object. This tribble call is the reason
187 // why we need a fall-back implementation in CompressorChannel
188 // of the methods compressStream() and decompressStream().
189 $serialized = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($object));
191 // Serialize only given attributes in a special container
192 $container = SerializationContainer::createSerializationContainer($this->getLimitInstance(), $object);
194 // Serialize the container
195 $serialized = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($container));
198 // Return the serialized object string
203 * Analyses if a unique ID has already been used or not by search in the
204 * local database folder.
206 * @param $uniqueID A unique ID number which shall be checked
207 * before it will be used
208 * @param $inConstructor If we got called in a de/con-structor or
209 * from somewhere else
210 * @return $isUnused true = The unique ID was not found in the database,
211 * false = It is already in use by an other object
212 * @throws NoArrayCreatedException If explode() fails to create an array
213 * @throws InvalidArrayCountException If the array contains less or
214 * more than two elements
216 public function isUniqueIdUsed ($uniqueID, $inConstructor = false) {
217 // Currently not used... ;-)
220 // Split the unique ID up in path and file name
221 $pathFile = explode("@", $uniqueID);
223 // Are there two elements? Index 0 is the path, 1 the file name + global extension
224 if (!is_array($pathFile)) {
226 if ($inConstructor) {
229 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
231 } elseif (count($pathFile) != 2) {
232 // Invalid ID returned!
233 if ($inConstructor) {
236 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
240 // Create full path name
241 $pathName = $this->getSavePath() . $pathFile[0];
243 // Check if the file is there with a file handler
244 if ($inConstructor) {
245 // No exceptions in constructors and destructors!
246 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName, true);
248 // Has an object being created?
249 if (!is_object($dirInstance)) return false;
251 // Outside a constructor
253 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
254 } catch (PathIsNoDirectoryException $e) {
255 // Okay, path not found
260 // Initialize the search loop
262 while ($dataFile = $dirInstance->readDirectoryExcept(array(".", "..", ".htaccess"))) {
263 // Generate FQFN for testing
264 $fqfn = sprintf("%s/%s", $pathName, $dataFile);
265 $this->setLastFile($fqfn);
267 // Get instance for file handler
268 $inputHandler = $this->getFileIoInstance();
270 // Try to read from it. This makes it sure that the file is
271 // readable and a valid database file
272 $this->setLastFileContents($inputHandler->loadFileContents($fqfn));
274 // Extract filename (= unique ID) from it
275 $ID = substr(basename($fqfn), 0, -(strlen($this->getFileExtension()) + 1));
277 // Is this the required unique ID?
278 if ($ID == $pathFile[1]) {
279 // Okay, already in use!
284 // Close the directory handler
285 $dirInstance->closeDirectory();
287 // Now the same for the file...
292 * Setter for the last read file
294 * @param $fqfn The FQFN of the last read file
297 private final function setLastFile ($fqfn) {
299 $fqfn = (string) $fqfn;
300 $this->lastFile = $fqfn;
304 * Reset the last error and exception instance. This should be done after
305 * a successfull "query"
309 private final function resetLastError () {
310 $this->lastError = "";
311 $this->lastException = null;
315 * Getter for last read file
317 * @return $lastFile The last read file's name with full path
319 public final function getLastFile () {
320 return $this->lastFile;
324 * Setter for contents of the last read file
326 * @param $contents An array with header and data elements
329 private final function setLastFileContents ($contents) {
331 $contents = (array) $contents;
332 $this->lastContents = $contents;
336 * Getter for last read file's content as an array
338 * @return $lastContent The array with elements 'header' and 'data'.
340 public final function getLastContents () {
341 return $this->lastContents;
345 * Getter for file extension
347 * @return $fileExtension The array with elements 'header' and 'data'.
349 public final function getFileExtension () {
350 return $this->fileExtension;
354 * Get cached (last fetched) data from the local file database
356 * @param $uniqueID The ID number for looking up the data
357 * @return $object The restored object from the maybe compressed
359 * @throws MismatchingCompressorsException If the compressor from
361 * mismatches with the
363 * @throws NullPointerException If the restored object
365 * @throws NoObjectException If the restored "object"
366 * is not an object instance
367 * @throws MissingMethodException If the required method
368 * toString() is missing
370 public final function getObjectFromCachedData ($uniqueID) {
371 // Get instance for file handler
372 $inputHandler = $this->getFileIoInstance();
374 // Get last file's name and contents
375 $fqfn = $this->repairFQFN($this->getLastFile(), $uniqueID);
376 $contents = $this->repairContents($this->getLastContents(), $fqfn);
378 // Let's decompress it. First we need the instance
379 $compressInstance = $this->getCompressorChannel();
381 // Is the compressor's extension the same as the one from the data?
382 if ($compressInstance->getCompressorExtension() != $contents['header'][0]) {
384 * @todo For now we abort here but later we need to make this a little more dynamic.
386 throw new MismatchingCompressorsException(array($this, $contents['header'][0], $fqfn, $compressInstance->getCompressorExtension()), self::EXCEPTION_MISMATCHING_COMPRESSORS);
389 // Decompress the data now
390 $serialized = $compressInstance->getCompressor()->decompressStream($contents['data']);
392 // And unserialize it...
393 $object = unserialize($serialized);
395 // This must become a valid object, so let's check it...
396 if (is_null($object)) {
397 // Is null, throw exception
398 throw new NullPointerException($object, self::EXCEPTION_IS_NULL_POINTER);
399 } elseif (!is_object($object)) {
400 // Is not an object, throw exception
401 throw new NoObjectException($object, self::EXCEPTION_IS_NO_OBJECT);
402 } elseif (!$object instanceof FrameworkInterface) {
403 // A highly required method was not found... :-(
404 throw new MissingMethodException(array($object, '__toString'), self::EXCEPTION_MISSING_METHOD);
407 // And return the object
412 * Private method for re-gathering (repairing) the FQFN
414 * @param $fqfn The current FQFN we shall validate
415 * @param $uniqueID The unique ID number
416 * @return $fqfn The repaired FQFN when it is empty
417 * @throws NoArrayCreatedException If explode() has not
419 * @throws InvalidArrayCountException If the array count is not
422 private function repairFQFN ($fqfn, $uniqueID) {
424 $fqfn = (string) $fqfn;
425 $uniqueID = (string) $uniqueID;
427 // Is there pre-cached data available?
429 // Split the unique ID up in path and file name
430 $pathFile = explode("@", $uniqueID);
432 // Are there two elements? Index 0 is the path, 1 the file name + global extension
433 if (!is_array($pathFile)) {
435 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
436 } elseif (count($pathFile) != 2) {
437 // Invalid ID returned!
438 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
441 // Create full path name
442 $pathName = $this->getSavePath() . $pathFile[0];
444 // Nothing cached, so let's create a FQFN first
445 $fqfn = sprintf("%s/%s.%s", $pathName, $pathFile[1], $this->getFileExtension());
446 $this->setLastFile($fqfn);
449 // Return repaired FQFN
454 * Private method for re-gathering the contents of a given file
456 * @param $contents The (maybe) already cached contents as an array
457 * @param $fqfn The current FQFN we shall validate
458 * @return $contents The repaired contents from the given file
460 private function repairContents ($contents, $fqfn) {
461 // Is there some content and header (2 indexes) in?
462 if ((!is_array($contents)) || (count($contents) != 2) || (!isset($contents['header'])) || (!isset($contents['data']))) {
463 // No content found so load the file again
464 $contents = $inputHandler->loadFileContents($fqfn);
466 // And remember all data for later usage
467 $this->setLastContents($contents);
470 // Return the repaired contents
475 * Makes sure that the database connection is alive
479 public function connectToDatabase () {
480 // @TODO Do some checks on the database directory and files here
484 * Loads data saved with saveObject from the database and re-creates a
485 * full object from it.
486 * If limitObject() was called before a new object ObjectContainer with
487 * all requested attributes will be returned instead.
489 * @return Object The fully re-created object or instance to
491 * @throws SavePathIsEmptyException If the given save path is an
493 * @throws SavePathIsNoDirectoryException If the save path is no
495 * @throws SavePathReadProtectedException If the save path is read-
497 * @throws SavePathWriteProtectedException If the save path is write-
500 public function loadObject () {
501 // Already connected? Then abort here
502 if ($this->alreadyConnected === true) return true;
505 $savePath = $this->getSavePath();
507 if (empty($savePath)) {
509 throw new SavePathIsEmptyException($dbInstance, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
510 } elseif (!is_dir($savePath)) {
512 throw new SavePathIsNoDirectoryException($savePath, self::EXCEPTION_INVALID_PATH_NAME);
513 } elseif (!is_readable($savePath)) {
515 throw new SavePathReadProtectedException($savePath, self::EXCEPTION_READ_PROTECED_PATH);
516 } elseif (!is_writeable($savePath)) {
517 // Path not writeable
518 throw new SavePathWriteProtectedException($savePath, self::EXCEPTION_WRITE_PROTECED_PATH);
521 // "Connection" established... ;-)
522 $this->alreadyConnected = true;
526 * Starts a SELECT query on the database by given return type, table name
527 * and search criteria
529 * @param $resultType Result type ("array", "object" and "indexed" are valid)
530 * @param $tableName Name of the database table
531 * @param $criteria Local search criteria class
532 * @return $resultData Result data of the query
533 * @throws UnsupportedCriteriaException If the criteria is unsupported
534 * @throws SqlException If an "SQL error" occurs
536 public function querySelect ($resultType, $tableName, Criteria $criteriaInstance) {
537 // The result is null by any errors
540 // Is this criteria supported?
541 if (!$criteriaInstance instanceof LocalSearchCriteria) {
542 // Not supported by this database layer
543 throw new UnsupportedCriteriaException(array($this, $criteriaInstance), self::EXCEPTION_REQUIRED_INTERFACE_MISSING);
546 // Create full path name
547 $pathName = $this->getSavePath() . $tableName . '/';
549 // A "select" query is not that easy on local files, so first try to
550 // find the "table" which is in fact a directory on the server
552 // Get a directory pointer instance
553 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
555 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
561 // Read the directory with some exceptions
562 while ($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess"))) {
563 $this->partialStub(sprintf("File %s found.", $dataFile));
566 // Close directory and throw the instance away
567 $directoryInstance->closeDirectory();
568 unset($directoryInstance);
570 // Reset last error message and exception
571 $this->resetLastError();
572 } catch (PathIsNoDirectoryException $e) {
573 // Path not found means "table not found" for real databases...
574 $this->lastException = $e;
575 $this->lastError = $e->getMessage();
577 // So throw an SqlException here with faked error message
578 throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
579 } catch (FrameworkException $e) {
580 // Catch all exceptions and store them in last error
581 $this->lastException = $e;
582 $this->lastError = $e->getMessage();
585 // Return the gathered result
590 * "Inserts" a data set instance into a local file database folder
592 * @param $dataSetInstance A storeable data set
595 public function insertDataSet (StoreableCriteria $dataSetInstance) {
596 // Create full path name
597 $fqfn = sprintf("%s%s/%s.%s",
598 $this->getSavePath(),
599 $dataSetInstance->getTableName(),
600 $dataSetInstance->getCombinedUniqueKey(),
601 $this->getFileExtension()
605 // Try to save the request away
607 // Get a file pointer instance
609 // Reset last error message and exception
610 $this->resetLastError();
611 } catch (FrameworkException $e) {
612 // Catch all exceptions and store them in last error
613 $this->lastException = $e;
614 $this->lastError = $e->getMessage();