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 last read file's name
40 private $lastFile = "";
43 * The last read file's content including header information
45 private $lastContents = array();
48 * The private constructor. Do never instance from outside!
49 * You need to set a local file path. The class will then validate it.
53 private function __construct() {
54 // Call parent constructor
55 parent::constructor(__CLASS__);
58 $this->setPartDescr("Dateidatenbankschicht");
61 $this->createUniqueID();
64 $this->removeSystemArray();
68 * Create an object of LocalFileDatabase and set the save path for local files.
69 * This method also validates the given file path.
71 * @param $savePath The local file path string
72 * @param $ioInstance The input/output handler. This
73 * should be FileIOHandler
74 * @return $dbInstance An instance of LocalFileDatabase
75 * @throws SavePathIsEmptyException If the given save path is an
77 * @throws SavePathIsNoDirectoryException If the save path is no
79 * @throws SavePathReadProtectedException If the save path is read-
81 * @throws SavePathWriteProtectedException If the save path is write-
84 public final static function createLocalFileDatabase ($savePath, FileIOHandler $ioInstance) {
86 $dbInstance = new LocalFileDatabase();
88 if (empty($savePath)) {
90 throw new SavePathIsEmptyException($dbInstance, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
91 } elseif (!is_dir($savePath)) {
93 throw new SavePathIsNoDirectoryException($savePath, self::EXCEPTION_INVALID_PATH_NAME);
94 } elseif (!is_readable($savePath)) {
96 throw new SavePathReadProtectedException($savePath, self::EXCEPTION_READ_PROTECED_PATH);
97 } elseif (!is_writeable($savePath)) {
99 throw new SavePathWriteProtectedException($savePath, self::EXCEPTION_WRITE_PROTECED_PATH);
103 if (defined('DEBUG_DATABASE')) $dbInstance->getDebugInstance()->output(sprintf("[%s:] Es werden lokale Dateien zum Speichern von Objekten verwendet.<br />\n",
104 $dbInstance->__toString()
107 // Set save path and IO instance
108 $dbInstance->setSavePath($savePath);
109 $dbInstance->setFileIOInstance($ioInstance);
111 // Return database instance
116 * Setter for save path
118 * @param $savePath The local save path where we shall put our serialized classes
121 public final function setSavePath ($savePath) {
123 $savePath = (string) $savePath;
126 if ((defined('DEBUG_DATABASE')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:] Lokaler Speicherpfad <strong>%s</strong> wird verwendet.<br />\n",
132 $this->savePath = $savePath;
136 * Getter for save path
138 * @return $savePath The local save path where we shall put our serialized classes
140 public final function getSavePath () {
141 return $this->savePath;
145 * Saves a given object to the local file system by serializing and
146 * transparently compressing it
148 * @param $object The object we shall save to the local file system
150 * @throws NullPointerException If the object instance is null
151 * @throws NoObjectException If the parameter $object is not
154 public final function saveObject ($object) {
155 // Some tests on the parameter...
156 if (is_null($object)) {
157 // Is null, throw exception
158 throw new NullPointerException($object, self::EXCEPTION_IS_NULL_POINTER);
159 } elseif (!is_object($object)) {
160 // Is not an object, throw exception
161 throw new NoObjectException($object, self::EXCEPTION_IS_NO_OBJECT);
162 } elseif (!method_exists($object, '__toString')) {
163 // A highly required method was not found... :-(
164 throw new MissingMethodException(array($object, '__toString'), self::EXCEPTION_MISSING_METHOD);
168 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",
170 $object->__toString()
173 // Get a string containing the serialized object. We cannot exchange
174 // $this and $object here because $object does not need to worry
175 // about it's limitations... ;-)
176 $serialized = $this->serializeObject($object);
179 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",
181 $object->__toString(),
185 // Get a path name plus file name and append the extension
186 $fqfn = $this->getSavePath() . $object->getPathFileNameFromObject() . "." . $this->getFileExtension();
188 // Save the file to disc we don't care here if the path is there,
189 // this must be done in later methods.
190 $this->getFileIOInstance()->saveFile($fqfn, array($this->getCompressorChannel()->getCompressorExtension(), $serialized));
194 * Get a serialized string from the given object
196 * @param $object The object we want to serialize and transparently
198 * @return $serialized A string containing the serialzed/compressed object
199 * @see ObjectLimits An object holding limition information
200 * @see SerializationContainer A special container class for e.g.
201 * attributes from limited objects
203 private function serializeObject ($object) {
204 // If there is no limiter instance we serialize the whole object
205 // otherwise only in the limiter object (ObjectLimits) specified
206 // attributes summarized in a special container class
207 if ($this->getLimitInstance() === null) {
208 // Serialize the whole object. This tribble call is the reason
209 // why we need a fall-back implementation in CompressorChannel
210 // of the methods compressStream() and decompressStream().
211 $serialized = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($object));
213 // Serialize only given attributes in a special container
214 $container = SerializationContainer::createSerializationContainer($this->getLimitInstance(), $object);
216 // Serialize the container
217 $serialized = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($container));
220 // Return the serialized object string
225 * Analyses if a unique ID has already been used or not by search in the
226 * local database folder.
228 * @param $uniqueID A unique ID number which shall be checked
229 * before it will be used
230 * @param $inConstructor If we got called in a de/con-structor or
231 * from somewhere else
232 * @return $isUnused true = The unique ID was not found in the database,
233 * false = It is already in use by an other object
234 * @throws NoArrayCreatedException If explode() fails to create an array
235 * @throws InvalidArrayCountException If the array contains less or
236 * more than two elements
238 public function isUniqueIdUsed ($uniqueID, $inConstructor = false) {
239 // Currently not used... ;-)
242 // Split the unique ID up in path and file name
243 $pathFile = explode("@", $uniqueID);
245 // Are there two elements? Index 0 is the path, 1 the file name + global extension
246 if (!is_array($pathFile)) {
248 if ($inConstructor) {
251 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
253 } elseif (count($pathFile) != 2) {
254 // Invalid ID returned!
255 if ($inConstructor) {
258 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
262 // Create full path name
263 $pathName = $this->getSavePath() . $pathFile[0];
265 // Check if the file is there with a file handler
266 if ($inConstructor) {
267 // No exceptions in constructors and destructors!
268 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName, true);
270 // Has an object being created?
271 if (!is_object($dirInstance)) return false;
273 // Outside a constructor
275 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
276 } catch (PathIsNoDirectoryException $e) {
277 // Okay, path not found
282 // Initialize the search loop
284 while ($dataFile = $dirInstance->readDirectoryExcept(array(".", ".."))) {
285 // Generate FQFN for testing
286 $fqfn = sprintf("%s/%s", $pathName, $dataFile);
287 $this->setLastFile($fqfn);
289 // Get instance for file handler
290 $inputHandler = $this->getFileIOInstance();
292 // Try to read from it. This makes it sure that the file is
293 // readable and a valid database file
294 $this->setLastFileContents($inputHandler->loadFileContents($fqfn));
296 // Extract filename (= unique ID) from it
297 $ID = substr(basename($fqfn), 0, -(strlen($this->getFileExtension()) + 1));
299 // Is this the required unique ID?
300 if ($ID == $pathFile[1]) {
301 // Okay, already in use!
306 // Close the directory handler
307 $dirInstance->closeDirectory();
309 // Now the same for the file...
314 * Setter for the last read file
316 * @param $fqfn The FQFN of the last read file
319 private final function setLastFile ($fqfn) {
321 $fqfn = (string) $fqfn;
322 $this->lastFile = $fqfn;
326 * Getter for last read file
328 * @return $lastFile The last read file's name with full path
330 public final function getLastFile () {
331 return $this->lastFile;
335 * Setter for contents of the last read file
337 * @param $contents An array with header and data elements
340 private final function setLastFileContents ($contents) {
342 $contents = (array) $contents;
343 $this->lastContents = $contents;
347 * Getter for last read file's content as an array
349 * @return $lastContent The array with elements 'header' and 'data'.
351 public final function getLastContents () {
352 return $this->lastContents;
356 * Get cached (last fetched) data from the local file database
358 * @param $uniqueID The ID number for looking up the data
359 * @return $object The restored object from the maybe compressed
361 * @throws MismatchingCompressorsException If the compressor from
363 * mismatches with the
365 * @throws NullPointerException If the restored object
367 * @throws NoObjectException If the restored "object"
368 * is not an object instance
369 * @throws MissingMethodException If the required method
370 * toString() is missing
372 public final function getObjectFromCachedData ($uniqueID) {
373 // Get instance for file handler
374 $inputHandler = $this->getFileIOInstance();
376 // Get last file's name and contents
377 $fqfn = $this->repairFQFN($this->getLastFile(), $uniqueID);
378 $contents = $this->repairContents($this->getLastContents(), $fqfn);
380 // Let's decompress it. First we need the instance
381 $compressInstance = $this->getCompressorChannel();
383 // Is the compressor's extension the same as the one from the data?
384 if ($compressInstance->getCompressorExtension() != $contents['header'][0]) {
386 * @todo For now we abort here but later we need to make this a little more dynamic.
388 throw new MismatchingCompressorsException(array($this, $contents['header'][0], $fqfn, $compressInstance->getCompressorExtension()), self::EXCEPTION_MISMATCHING_COMPRESSORS);
391 // Decompress the data now
392 $serialized = $compressInstance->getCompressor()->decompressStream($contents['data']);
394 // And unserialize it...
395 $object = unserialize($serialized);
397 // This must become a valid object, so let's check it...
398 if (is_null($object)) {
399 // Is null, throw exception
400 throw new NullPointerException($object, self::EXCEPTION_IS_NULL_POINTER);
401 } elseif (!is_object($object)) {
402 // Is not an object, throw exception
403 throw new NoObjectException($object, self::EXCEPTION_IS_NO_OBJECT);
404 } elseif (!method_exists($object, '__toString')) {
405 // A highly required method was not found... :-(
406 throw new MissingMethodException(array($object, '__toString'), self::EXCEPTION_MISSING_METHOD);
409 // And return the object
414 * Private method for re-gathering (repairing) the FQFN
416 * @param $fqfn The current FQFN we shall validate
417 * @param $uniqueID The unique ID number
418 * @return $fqfn The repaired FQFN when it is empty
419 * @throws NoArrayCreatedException If explode() has not
421 * @throws InvalidArrayCountException If the array count is not
424 private function repairFQFN ($fqfn, $uniqueID) {
426 $fqfn = (string) $fqfn;
427 $uniqueID = (string) $uniqueID;
429 // Is there pre-cached data available?
431 // Split the unique ID up in path and file name
432 $pathFile = explode("@", $uniqueID);
434 // Are there two elements? Index 0 is the path, 1 the file name + global extension
435 if (!is_array($pathFile)) {
437 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
438 } elseif (count($pathFile) != 2) {
439 // Invalid ID returned!
440 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
443 // Create full path name
444 $pathName = $this->getSavePath() . $pathFile[0];
446 // Nothing cached, so let's create a FQFN first
447 $fqfn = sprintf("%s/%s.%s", $pathName, $pathFile[1], $this->getFileExtension());
448 $this->setLastFile($fqfn);
451 // Return repaired FQFN
456 * Private method for re-gathering the contents of a given file
458 * @param $contents The (maybe) already cached contents as an array
459 * @param $fqfn The current FQFN we shall validate
460 * @return $contents The repaired contents from the given file
462 private function repairContents ($contents, $fqfn) {
463 // Is there some content and header (2 indexes) in?
464 if ((!is_array($contents)) || (count($contents) != 2) || (!isset($contents['header'])) || (!isset($contents['data']))) {
465 // No content found so load the file again
466 $contents = $inputHandler->loadFileContents($fqfn);
468 // And remember all data for later usage
469 $this->setLastContents($contents);
472 // Return the repaired contents
476 /* DUMMY */ public final function loadObject () {}