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@mxchange.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.mxchange.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 IO handler for file handling which should be FileIOHandler.
40 private $ioInstance = null;
43 * The last read file's name
45 private $lastFile = "";
48 * The last read file's content including header information
50 private $lastContents = array();
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 private function __construct() {
59 // Call parent constructor
60 parent::constructor(__CLASS__);
63 $this->setPartDescr("Dateidatenbankschicht");
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
80 * @throws SavePathIsEmptyException If the given save path is an
82 * @throws SavePathIsNoDirectoryException If the save path is no
84 * @throws SavePathReadProtectedException If the save path is read-
86 * @throws SavePathWriteProtectedException If the save path is write-
89 public final static function createLocalFileDatabase ($savePath, FileIOHandler $ioInstance) {
91 $dbInstance = new LocalFileDatabase();
93 if (empty($savePath)) {
95 throw new SavePathIsEmptyException($dbInstance, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
96 } elseif (!is_dir($savePath)) {
98 throw new SavePathIsNoDirectoryException($savePath, self::EXCEPTION_INVALID_PATH_NAME);
99 } elseif (!is_readable($savePath)) {
101 throw new SavePathReadProtectedException($savePath, self::EXCEPTION_READ_PROTECED_PATH);
102 } elseif (!is_writeable($savePath)) {
103 // Path not writeable
104 throw new SavePathWriteProtectedException($savePath, self::EXCEPTION_WRITE_PROTECED_PATH);
108 if (defined('DEBUG_DATABASE')) $dbInstance->getDebugInstance()->output(sprintf("[%s:] Es werden lokale Dateien zum Speichern von Objekten verwendet.<br />\n",
109 $dbInstance->__toString()
112 // Set save path and IO instance
113 $dbInstance->setSavePath($savePath);
114 $dbInstance->setIOInstance($ioInstance);
116 // Return database instance
121 * Setter for save path
123 * @param $savePath The local save path where we shall put our serialized classes
126 public final function setSavePath ($savePath) {
128 $savePath = (string) $savePath;
131 if ((defined('DEBUG_DATABASE')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:] Lokaler Speicherpfad <strong>%s</strong> wird verwendet.<br />\n",
137 $this->savePath = $savePath;
141 * Getter for save path
143 * @return $savePath The local save path where we shall put our serialized classes
145 public final function getSavePath () {
146 return $this->savePath;
150 * Getter for file extension
152 * @return $fileExtension The file extension for all file names
154 public final function getFileExtension () {
155 return $this->fileExtension;
159 * Saves a given object to the local file system by serializing and
160 * transparently compressing it
162 * @param $object The object we shall save to the local file system
164 * @throws NullPointerException If the object instance is null
165 * @throws NoObjectException If the parameter $object is not
168 public final function saveObject ($object) {
169 // Some tests on the parameter...
170 if (is_null($object)) {
171 // Is null, throw exception
172 throw new NullPointerException($object, self::EXCEPTION_IS_NULL_POINTER);
173 } elseif (!is_object($object)) {
174 // Is not an object, throw exception
175 throw new NoObjectException($object, self::EXCEPTION_IS_NO_OBJECT);
176 } elseif (!method_exists($object, '__toString')) {
177 // A highly required method was not found... :-(
178 throw new MissingMethodException(array($object, '__toString'), self::EXCEPTION_MISSING_METHOD);
182 if ((defined('DEBUG_DATABASE')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:] Das Objekt <strong>%s</strong> soll in eine lokale Datei gespeichert werden.<br />\n",
184 $object->__toString()
187 // Get a string containing the serialized object. We cannot exchange
188 // $this and $object here because $object does not need to worry
189 // about it's limitations... ;-)
190 $serialized = $this->serializeObject($object);
193 if ((defined('DEBUG_DATABASE')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:] Das Objekt <strong>%s</strong> ist nach der Serialisierung <strong>%s</strong> Byte gross.<br />\n",
195 $object->__toString(),
199 // Get a path name plus file name and append the extension
200 $fqfn = $this->getSavePath() . $object->getPathFileNameFromObject() . "." . $this->getFileExtension();
202 // Save the file to disc we don't care here if the path is there,
203 // this must be done in later methods.
204 $this->getIOInstance()->saveFile($fqfn, array($this->getCompressorChannel()->getCompressorExtension(), $serialized));
208 * Get a serialized string from the given object
210 * @param $object The object we want to serialize and transparently
212 * @return $serialized A string containing the serialzed/compressed object
213 * @see ObjectLimits An object holding limition information
214 * @see SerializationContainer A special container class for e.g.
215 * attributes from limited objects
217 private function serializeObject ($object) {
218 // If there is no limiter instance we serialize the whole object
219 // otherwise only in the limiter object (ObjectLimits) specified
220 // attributes summarized in a special container class
221 if ($this->getLimitInstance() === null) {
222 // Serialize the whole object. This tribble call is the reason
223 // why we need a fall-back implementation in CompressorChannel
224 // of the methods compressStream() and decompressStream().
225 $serialized = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($object));
227 // Serialize only given attributes in a special container
228 $container = SerializationContainer::createSerializationContainer($this->getLimitInstance(), $object);
230 // Serialize the container
231 $serialized = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($container));
234 // Return the serialized object string
239 * Analyses if a unique ID has already been used or not by search in the
240 * local database folder.
242 * @param $uniqueID A unique ID number which shall be checked
243 * before it will be used
244 * @param $inConstructor If we got called in a de/con-structor or
245 * from somewhere else
246 * @return $isUnused true = The unique ID was not found in the database,
247 * false = It is already in use by an other object
248 * @throws NoArrayCreatedException If explode() fails to create an array
249 * @throws InvalidArrayCountException If the array contains less or
250 * more than two elements
252 public function isUniqueIdUsed ($uniqueID, $inConstructor = false) {
253 // Currently not used... ;-)
256 // Split the unique ID up in path and file name
257 $pathFile = explode("@", $uniqueID);
259 // Are there two elements? Index 0 is the path, 1 the file name + global extension
260 if (!is_array($pathFile)) {
262 if ($inConstructor) {
265 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
267 } elseif (count($pathFile) != 2) {
268 // Invalid ID returned!
269 if ($inConstructor) {
272 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
276 // Create full path name
277 $pathName = $this->getSavePath() . $pathFile[0];
279 // Check if the file is there with a file handler
280 if ($inConstructor) {
281 // No exceptions in constructors and destructors!
282 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName, true);
284 // Has an object being created?
285 if (!is_object($dirInstance)) return false;
287 // Outside a constructor
289 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
290 } catch (PathIsNoDirectoryException $e) {
291 // Okay, path not found
296 // Initialize the search loop
298 while ($dataFile = $dirInstance->readDirectoryExcept(array(".", ".."))) {
299 // Generate FQFN for testing
300 $fqfn = sprintf("%s/%s", $pathName, $dataFile);
301 $this->setLastFile($fqfn);
303 // Get instance for file handler
304 $inputHandler = $this->getIOInstance();
306 // Try to read from it. This makes it sure that the file is
307 // readable and a valid database file
308 $this->setLastFileContents($inputHandler->loadFileContents($fqfn));
310 // Extract filename (= unique ID) from it
311 $ID = substr(basename($fqfn), 0, -(strlen($this->getFileExtension()) + 1));
313 // Is this the required unique ID?
314 if ($ID == $pathFile[1]) {
315 // Okay, already in use!
320 // Close the directory handler
321 $dirInstance->closeDirectory();
323 // Now the same for the file...
328 * Getter for the file IO instance
330 *�@return $ioInstance An instance for IO operations
331 * @see FileIOHandler The concrete handler for IO operations
333 public final function getIOInstance () {
334 return $this->ioInstance;
338 * Setter for the file IO instance
340 * @param $ioInstance An instance for IO operations (should be
344 public final function setIOInstance (FileIOHandler $ioInstance) {
345 $this->ioInstance = $ioInstance;
349 * Setter for the last read file
351 * @param $fqfn The FQFN of the last read file
354 private function setLastFile ($fqfn) {
356 $fqfn = (string) $fqfn;
357 $this->lastFile = $fqfn;
361 * Getter for last read file
363 * @return $lastFile The last read file's name with full path
365 public final function getLastFile () {
366 return $this->lastFile;
370 * Setter for contents of the last read file
372 * @param $contents An array with header and data elements
375 private function setLastFileContents ($contents) {
377 $contents = (array) $contents;
378 $this->lastContents = $contents;
382 * Getter for last read file's content as an array
384 * @return $lastContent The array with elements 'header' and 'data'.
386 public final function getLastContents () {
387 return $this->lastContents;
391 * Get cached (last fetched) data from the local file database
393 * @param $uniqueID The ID number for looking up the data
394 * @return $object The restored object from the maybe compressed
396 * @throws MismatchingCompressorsException If the compressor from
398 * mismatches with the
400 * @throws NullPointerException If the restored object
402 * @throws NoObjectException If the restored "object"
403 * is not an object instance
404 * @throws MissingMethodException If the required method
405 * toString() is missing
407 public function getObjectFromCachedData ($uniqueID) {
408 // Get instance for file handler
409 $inputHandler = $this->getIOInstance();
411 // Get last file's name and contents
412 $fqfn = $this->repairFQFN($this->getLastFile(), $uniqueID);
413 $contents = $this->repairContents($this->getLastContents(), $fqfn);
415 // Let's decompress it. First we need the instance
416 $compressInstance = $this->getCompressorChannel();
418 // Is the compressor's extension the same as the one from the data?
419 if ($compressInstance->getCompressorExtension() != $contents['header'][0]) {
421 * @todo For now we abort here but later we need to make this a little more dynamic.
423 throw new MismatchingCompressorsException(array($this, $contents['header'][0], $fqfn, $compressInstance->getCompressorExtension()), self::EXCEPTION_MISMATCHING_COMPRESSORS);
426 // Decompress the data now
427 $serialized = $compressInstance->getCompressor()->decompressStream($contents['data']);
429 // And unserialize it...
430 $object = unserialize($serialized);
432 // This must become a valid object, so let's check it...
433 if (is_null($object)) {
434 // Is null, throw exception
435 throw new NullPointerException($object, self::EXCEPTION_IS_NULL_POINTER);
436 } elseif (!is_object($object)) {
437 // Is not an object, throw exception
438 throw new NoObjectException($object, self::EXCEPTION_IS_NO_OBJECT);
439 } elseif (!method_exists($object, '__toString')) {
440 // A highly required method was not found... :-(
441 throw new MissingMethodException(array($object, '__toString'), self::EXCEPTION_MISSING_METHOD);
444 // And return the object
449 * Private method for re-gathering (repairing) the FQFN
451 * @param $fqfn The current FQFN we shall validate
452 * @param $uniqueID The unique ID number
453 * @return $fqfn The repaired FQFN when it is empty
454 * @throws NoArrayCreatedException If explode() has not
456 * @throws InvalidArrayCountException If the array count is not
459 private function repairFQFN ($fqfn, $uniqueID) {
461 $fqfn = (string) $fqfn;
462 $uniqueID = (string) $uniqueID;
464 // Is there pre-cached data available?
466 // Split the unique ID up in path and file name
467 $pathFile = explode("@", $uniqueID);
469 // Are there two elements? Index 0 is the path, 1 the file name + global extension
470 if (!is_array($pathFile)) {
472 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
473 } elseif (count($pathFile) != 2) {
474 // Invalid ID returned!
475 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
478 // Create full path name
479 $pathName = $this->getSavePath() . $pathFile[0];
481 // Nothing cached, so let's create a FQFN first
482 $fqfn = sprintf("%s/%s.%s", $pathName, $pathFile[1], $this->getFileExtension());
483 $this->setLastFile($fqfn);
486 // Return repaired FQFN
491 * Private method for re-gathering the contents of a given file
493 * @param $contents The (maybe) already cached contents as an array
494 * @param $fqfn The current FQFN we shall validate
495 * @return $contents The repaired contents from the given file
497 private function repairContents ($contents, $fqfn) {
498 // Is there some content and header (2 indexes) in?
499 if ((!is_array($contents)) || (count($contents) != 2) || (!isset($contents['header'])) || (!isset($contents['data']))) {
500 // No content found so load the file again
501 $contents = $inputHandler->loadFileContents($fqfn);
503 // And remember all data for later usage
504 $this->setLastContents($contents);
507 // Return the repaired contents
511 /* DUMMY */ public final function loadObject () {}