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 {
28 * Save path for "file database"
30 private $savePath = "";
33 * The file's extension
35 private $fileExtension = "serialized";
38 * The last read file's name
40 private $lastFile = "";
43 * The last read file's content including header information
45 private $lastContents = array();
48 * Wether the "connection is already up
50 private $alreadyConnected = false;
53 * The private constructor. Do never instance from outside!
54 * You need to set a local file path. The class will then validate it.
58 protected function __construct() {
59 // Call parent constructor
60 parent::__construct(__CLASS__);
63 $this->setObjectDescription("Class for local file databases");
66 $this->createUniqueID();
69 $this->removeSystemArray();
73 * Create an object of LocalFileDatabase and set the save path for local files.
74 * This method also validates the given file path.
76 * @param $savePath The local file path string
77 * @param $ioInstance The input/output handler. This
78 * should be FileIoHandler
79 * @return $dbInstance An instance of LocalFileDatabase
81 public final static function createLocalFileDatabase ($savePath, FileIoHandler $ioInstance) {
83 $dbInstance = new LocalFileDatabase();
85 // Set save path and IO instance
86 $dbInstance->setSavePath($savePath);
87 $dbInstance->setFileIoInstance($ioInstance);
89 // "Connect" to the database
90 $dbInstance->connectToDatabase();
92 // Return database instance
97 * Setter for save path
99 * @param $savePath The local save path where we shall put our serialized classes
102 public final function setSavePath ($savePath) {
104 $savePath = (string) $savePath;
107 $this->savePath = $savePath;
111 * Getter for save path
113 * @return $savePath The local save path where we shall put our serialized classes
115 public final function getSavePath () {
116 return $this->savePath;
120 * Saves a given object to the local file system by serializing and
121 * transparently compressing it
123 * @param $object The object we shall save to the local file system
125 * @throws NullPointerException If the object instance is null
126 * @throws NoObjectException If the parameter $object is not
129 public final function saveObject ($object) {
130 // Some tests on the parameter...
131 if (is_null($object)) {
132 // Is null, throw exception
133 throw new NullPointerException($object, self::EXCEPTION_IS_NULL_POINTER);
134 } elseif (!is_object($object)) {
135 // Is not an object, throw exception
136 throw new NoObjectException($object, self::EXCEPTION_IS_NO_OBJECT);
137 } elseif (!method_exists($object, '__toString')) {
138 // A highly required method was not found... :-(
139 throw new MissingMethodException(array($object, '__toString'), self::EXCEPTION_MISSING_METHOD);
142 // Get a string containing the serialized object. We cannot exchange
143 // $this and $object here because $object does not need to worry
144 // about it's limitations... ;-)
145 $serialized = $this->serializeObject($object);
147 // Get a path name plus file name and append the extension
148 $fqfn = $this->getSavePath() . $object->getPathFileNameFromObject() . "." . $this->getFileExtension();
150 // Save the file to disc we don't care here if the path is there,
151 // this must be done in later methods.
152 $this->getFileIoInstance()->saveFile($fqfn, array($this->getCompressorChannel()->getCompressorExtension(), $serialized));
156 * Get a serialized string from the given object
158 * @param $object The object we want to serialize and transparently
160 * @return $serialized A string containing the serialzed/compressed object
161 * @see ObjectLimits An object holding limition information
162 * @see SerializationContainer A special container class for e.g.
163 * attributes from limited objects
165 private function serializeObject ($object) {
166 // If there is no limiter instance we serialize the whole object
167 // otherwise only in the limiter object (ObjectLimits) specified
168 // attributes summarized in a special container class
169 if ($this->getLimitInstance() === null) {
170 // Serialize the whole object. This tribble call is the reason
171 // why we need a fall-back implementation in CompressorChannel
172 // of the methods compressStream() and decompressStream().
173 $serialized = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($object));
175 // Serialize only given attributes in a special container
176 $container = SerializationContainer::createSerializationContainer($this->getLimitInstance(), $object);
178 // Serialize the container
179 $serialized = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($container));
182 // Return the serialized object string
187 * Analyses if a unique ID has already been used or not by search in the
188 * local database folder.
190 * @param $uniqueID A unique ID number which shall be checked
191 * before it will be used
192 * @param $inConstructor If we got called in a de/con-structor or
193 * from somewhere else
194 * @return $isUnused true = The unique ID was not found in the database,
195 * false = It is already in use by an other object
196 * @throws NoArrayCreatedException If explode() fails to create an array
197 * @throws InvalidArrayCountException If the array contains less or
198 * more than two elements
200 public function isUniqueIdUsed ($uniqueID, $inConstructor = false) {
201 // Currently not used... ;-)
204 // Split the unique ID up in path and file name
205 $pathFile = explode("@", $uniqueID);
207 // Are there two elements? Index 0 is the path, 1 the file name + global extension
208 if (!is_array($pathFile)) {
210 if ($inConstructor) {
213 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
215 } elseif (count($pathFile) != 2) {
216 // Invalid ID returned!
217 if ($inConstructor) {
220 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
224 // Create full path name
225 $pathName = $this->getSavePath() . $pathFile[0];
227 // Check if the file is there with a file handler
228 if ($inConstructor) {
229 // No exceptions in constructors and destructors!
230 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName, true);
232 // Has an object being created?
233 if (!is_object($dirInstance)) return false;
235 // Outside a constructor
237 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
238 } catch (PathIsNoDirectoryException $e) {
239 // Okay, path not found
244 // Initialize the search loop
246 while ($dataFile = $dirInstance->readDirectoryExcept(array(".", ".."))) {
247 // Generate FQFN for testing
248 $fqfn = sprintf("%s/%s", $pathName, $dataFile);
249 $this->setLastFile($fqfn);
251 // Get instance for file handler
252 $inputHandler = $this->getFileIoInstance();
254 // Try to read from it. This makes it sure that the file is
255 // readable and a valid database file
256 $this->setLastFileContents($inputHandler->loadFileContents($fqfn));
258 // Extract filename (= unique ID) from it
259 $ID = substr(basename($fqfn), 0, -(strlen($this->getFileExtension()) + 1));
261 // Is this the required unique ID?
262 if ($ID == $pathFile[1]) {
263 // Okay, already in use!
268 // Close the directory handler
269 $dirInstance->closeDirectory();
271 // Now the same for the file...
276 * Setter for the last read file
278 * @param $fqfn The FQFN of the last read file
281 private final function setLastFile ($fqfn) {
283 $fqfn = (string) $fqfn;
284 $this->lastFile = $fqfn;
288 * Getter for last read file
290 * @return $lastFile The last read file's name with full path
292 public final function getLastFile () {
293 return $this->lastFile;
297 * Setter for contents of the last read file
299 * @param $contents An array with header and data elements
302 private final function setLastFileContents ($contents) {
304 $contents = (array) $contents;
305 $this->lastContents = $contents;
309 * Getter for last read file's content as an array
311 * @return $lastContent The array with elements 'header' and 'data'.
313 public final function getLastContents () {
314 return $this->lastContents;
318 * Getter for file extension
320 * @return $fileExtension The array with elements 'header' and 'data'.
322 public final function getFileExtension () {
323 return $this->fileExtension;
327 * Get cached (last fetched) data from the local file database
329 * @param $uniqueID The ID number for looking up the data
330 * @return $object The restored object from the maybe compressed
332 * @throws MismatchingCompressorsException If the compressor from
334 * mismatches with the
336 * @throws NullPointerException If the restored object
338 * @throws NoObjectException If the restored "object"
339 * is not an object instance
340 * @throws MissingMethodException If the required method
341 * toString() is missing
343 public final function getObjectFromCachedData ($uniqueID) {
344 // Get instance for file handler
345 $inputHandler = $this->getFileIoInstance();
347 // Get last file's name and contents
348 $fqfn = $this->repairFQFN($this->getLastFile(), $uniqueID);
349 $contents = $this->repairContents($this->getLastContents(), $fqfn);
351 // Let's decompress it. First we need the instance
352 $compressInstance = $this->getCompressorChannel();
354 // Is the compressor's extension the same as the one from the data?
355 if ($compressInstance->getCompressorExtension() != $contents['header'][0]) {
357 * @todo For now we abort here but later we need to make this a little more dynamic.
359 throw new MismatchingCompressorsException(array($this, $contents['header'][0], $fqfn, $compressInstance->getCompressorExtension()), self::EXCEPTION_MISMATCHING_COMPRESSORS);
362 // Decompress the data now
363 $serialized = $compressInstance->getCompressor()->decompressStream($contents['data']);
365 // And unserialize it...
366 $object = unserialize($serialized);
368 // This must become a valid object, so let's check it...
369 if (is_null($object)) {
370 // Is null, throw exception
371 throw new NullPointerException($object, self::EXCEPTION_IS_NULL_POINTER);
372 } elseif (!is_object($object)) {
373 // Is not an object, throw exception
374 throw new NoObjectException($object, self::EXCEPTION_IS_NO_OBJECT);
375 } elseif (!$object instanceof FrameworkInterface) {
376 // A highly required method was not found... :-(
377 throw new MissingMethodException(array($object, '__toString'), self::EXCEPTION_MISSING_METHOD);
380 // And return the object
385 * Private method for re-gathering (repairing) the FQFN
387 * @param $fqfn The current FQFN we shall validate
388 * @param $uniqueID The unique ID number
389 * @return $fqfn The repaired FQFN when it is empty
390 * @throws NoArrayCreatedException If explode() has not
392 * @throws InvalidArrayCountException If the array count is not
395 private function repairFQFN ($fqfn, $uniqueID) {
397 $fqfn = (string) $fqfn;
398 $uniqueID = (string) $uniqueID;
400 // Is there pre-cached data available?
402 // Split the unique ID up in path and file name
403 $pathFile = explode("@", $uniqueID);
405 // Are there two elements? Index 0 is the path, 1 the file name + global extension
406 if (!is_array($pathFile)) {
408 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
409 } elseif (count($pathFile) != 2) {
410 // Invalid ID returned!
411 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
414 // Create full path name
415 $pathName = $this->getSavePath() . $pathFile[0];
417 // Nothing cached, so let's create a FQFN first
418 $fqfn = sprintf("%s/%s.%s", $pathName, $pathFile[1], $this->getFileExtension());
419 $this->setLastFile($fqfn);
422 // Return repaired FQFN
427 * Private method for re-gathering the contents of a given file
429 * @param $contents The (maybe) already cached contents as an array
430 * @param $fqfn The current FQFN we shall validate
431 * @return $contents The repaired contents from the given file
433 private function repairContents ($contents, $fqfn) {
434 // Is there some content and header (2 indexes) in?
435 if ((!is_array($contents)) || (count($contents) != 2) || (!isset($contents['header'])) || (!isset($contents['data']))) {
436 // No content found so load the file again
437 $contents = $inputHandler->loadFileContents($fqfn);
439 // And remember all data for later usage
440 $this->setLastContents($contents);
443 // Return the repaired contents
448 * Makes sure that the database connection is alive
452 public function connectToDatabase () {
453 // @TODO Do some checks on the database directory and files here
457 * Loads data saved with saveObject from the database and re-creates a
458 * full object from it.
459 * If limitObject() was called before a new object ObjectContainer with
460 * all requested attributes will be returned instead.
462 * @return Object The fully re-created object or instance to
464 * @throws SavePathIsEmptyException If the given save path is an
466 * @throws SavePathIsNoDirectoryException If the save path is no
468 * @throws SavePathReadProtectedException If the save path is read-
470 * @throws SavePathWriteProtectedException If the save path is write-
473 public function loadObject () {
474 // Already connected? Then abort here
475 if ($this->alreadyConnected === true) return true;
478 $savePath = $this->getSavePath();
480 if (empty($savePath)) {
482 throw new SavePathIsEmptyException($dbInstance, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
483 } elseif (!is_dir($savePath)) {
485 throw new SavePathIsNoDirectoryException($savePath, self::EXCEPTION_INVALID_PATH_NAME);
486 } elseif (!is_readable($savePath)) {
488 throw new SavePathReadProtectedException($savePath, self::EXCEPTION_READ_PROTECED_PATH);
489 } elseif (!is_writeable($savePath)) {
490 // Path not writeable
491 throw new SavePathWriteProtectedException($savePath, self::EXCEPTION_WRITE_PROTECED_PATH);
494 // "Connection" established... ;-)
495 $this->alreadyConnected = true;
499 * Starts a SELECT query on the database by given return type, table name
500 * and search criteria
502 * @param $resultType Result type ("array", "object" and "indexed" are valid)
503 * @param $tableName Name of the database table
504 * @param $criteria Local search criteria class
505 * @return $resultData Result data of the query
506 * @throws UnsupportedCriteriaException If the criteria is unsupported
508 public function querySelect ($resultType, $tableName, Criteria $criteriaInstance) {
509 // Is this criteria supported?
510 if (!$criteriaInstance instanceof LocalCriteria) {
511 // Not supported by this database layer
512 throw new UnsupportedCriteriaException(array($this, $criteriaInstance), self::EXCEPTION_REQUIRED_INTERFACE_MISSING);
515 // A "select" query on local files is not that easy, so begin slowly with it...
516 $this->partialStub(sprintf("type=%s,table=%s,criteria=%s", $resultType, $tableName, $criteriaInstance));