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.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 * The private constructor. Do never instance from outside!
49 * You need to set a local file path. The class will then validate it.
53 protected function __construct() {
54 // Call parent constructor
55 parent::__construct(__CLASS__);
58 $this->setObjectDescription("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);
102 // Set save path and IO instance
103 $dbInstance->setSavePath($savePath);
104 $dbInstance->setFileIOInstance($ioInstance);
106 // Return database instance
111 * Setter for save path
113 * @param $savePath The local save path where we shall put our serialized classes
116 public final function setSavePath ($savePath) {
118 $savePath = (string) $savePath;
121 $this->savePath = $savePath;
125 * Getter for save path
127 * @return $savePath The local save path where we shall put our serialized classes
129 public final function getSavePath () {
130 return $this->savePath;
134 * Saves a given object to the local file system by serializing and
135 * transparently compressing it
137 * @param $object The object we shall save to the local file system
139 * @throws NullPointerException If the object instance is null
140 * @throws NoObjectException If the parameter $object is not
143 public final function saveObject ($object) {
144 // Some tests on the parameter...
145 if (is_null($object)) {
146 // Is null, throw exception
147 throw new NullPointerException($object, self::EXCEPTION_IS_NULL_POINTER);
148 } elseif (!is_object($object)) {
149 // Is not an object, throw exception
150 throw new NoObjectException($object, self::EXCEPTION_IS_NO_OBJECT);
151 } elseif (!method_exists($object, '__toString')) {
152 // A highly required method was not found... :-(
153 throw new MissingMethodException(array($object, '__toString'), self::EXCEPTION_MISSING_METHOD);
156 // Get a string containing the serialized object. We cannot exchange
157 // $this and $object here because $object does not need to worry
158 // about it's limitations... ;-)
159 $serialized = $this->serializeObject($object);
161 // Get a path name plus file name and append the extension
162 $fqfn = $this->getSavePath() . $object->getPathFileNameFromObject() . "." . $this->getFileExtension();
164 // Save the file to disc we don't care here if the path is there,
165 // this must be done in later methods.
166 $this->getFileIOInstance()->saveFile($fqfn, array($this->getCompressorChannel()->getCompressorExtension(), $serialized));
170 * Get a serialized string from the given object
172 * @param $object The object we want to serialize and transparently
174 * @return $serialized A string containing the serialzed/compressed object
175 * @see ObjectLimits An object holding limition information
176 * @see SerializationContainer A special container class for e.g.
177 * attributes from limited objects
179 private function serializeObject ($object) {
180 // If there is no limiter instance we serialize the whole object
181 // otherwise only in the limiter object (ObjectLimits) specified
182 // attributes summarized in a special container class
183 if ($this->getLimitInstance() === null) {
184 // Serialize the whole object. This tribble call is the reason
185 // why we need a fall-back implementation in CompressorChannel
186 // of the methods compressStream() and decompressStream().
187 $serialized = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($object));
189 // Serialize only given attributes in a special container
190 $container = SerializationContainer::createSerializationContainer($this->getLimitInstance(), $object);
192 // Serialize the container
193 $serialized = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($container));
196 // Return the serialized object string
201 * Analyses if a unique ID has already been used or not by search in the
202 * local database folder.
204 * @param $uniqueID A unique ID number which shall be checked
205 * before it will be used
206 * @param $inConstructor If we got called in a de/con-structor or
207 * from somewhere else
208 * @return $isUnused true = The unique ID was not found in the database,
209 * false = It is already in use by an other object
210 * @throws NoArrayCreatedException If explode() fails to create an array
211 * @throws InvalidArrayCountException If the array contains less or
212 * more than two elements
214 public function isUniqueIdUsed ($uniqueID, $inConstructor = false) {
215 // Currently not used... ;-)
218 // Split the unique ID up in path and file name
219 $pathFile = explode("@", $uniqueID);
221 // Are there two elements? Index 0 is the path, 1 the file name + global extension
222 if (!is_array($pathFile)) {
224 if ($inConstructor) {
227 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
229 } elseif (count($pathFile) != 2) {
230 // Invalid ID returned!
231 if ($inConstructor) {
234 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
238 // Create full path name
239 $pathName = $this->getSavePath() . $pathFile[0];
241 // Check if the file is there with a file handler
242 if ($inConstructor) {
243 // No exceptions in constructors and destructors!
244 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName, true);
246 // Has an object being created?
247 if (!is_object($dirInstance)) return false;
249 // Outside a constructor
251 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
252 } catch (PathIsNoDirectoryException $e) {
253 // Okay, path not found
258 // Initialize the search loop
260 while ($dataFile = $dirInstance->readDirectoryExcept(array(".", ".."))) {
261 // Generate FQFN for testing
262 $fqfn = sprintf("%s/%s", $pathName, $dataFile);
263 $this->setLastFile($fqfn);
265 // Get instance for file handler
266 $inputHandler = $this->getFileIOInstance();
268 // Try to read from it. This makes it sure that the file is
269 // readable and a valid database file
270 $this->setLastFileContents($inputHandler->loadFileContents($fqfn));
272 // Extract filename (= unique ID) from it
273 $ID = substr(basename($fqfn), 0, -(strlen($this->getFileExtension()) + 1));
275 // Is this the required unique ID?
276 if ($ID == $pathFile[1]) {
277 // Okay, already in use!
282 // Close the directory handler
283 $dirInstance->closeDirectory();
285 // Now the same for the file...
290 * Setter for the last read file
292 * @param $fqfn The FQFN of the last read file
295 private final function setLastFile ($fqfn) {
297 $fqfn = (string) $fqfn;
298 $this->lastFile = $fqfn;
302 * Getter for last read file
304 * @return $lastFile The last read file's name with full path
306 public final function getLastFile () {
307 return $this->lastFile;
311 * Setter for contents of the last read file
313 * @param $contents An array with header and data elements
316 private final function setLastFileContents ($contents) {
318 $contents = (array) $contents;
319 $this->lastContents = $contents;
323 * Getter for last read file's content as an array
325 * @return $lastContent The array with elements 'header' and 'data'.
327 public final function getLastContents () {
328 return $this->lastContents;
332 * Getter for file extension
334 * @return $fileExtension The array with elements 'header' and 'data'.
336 public final function getFileExtension () {
337 return $this->fileExtension;
341 * Get cached (last fetched) data from the local file database
343 * @param $uniqueID The ID number for looking up the data
344 * @return $object The restored object from the maybe compressed
346 * @throws MismatchingCompressorsException If the compressor from
348 * mismatches with the
350 * @throws NullPointerException If the restored object
352 * @throws NoObjectException If the restored "object"
353 * is not an object instance
354 * @throws MissingMethodException If the required method
355 * toString() is missing
357 public final function getObjectFromCachedData ($uniqueID) {
358 // Get instance for file handler
359 $inputHandler = $this->getFileIOInstance();
361 // Get last file's name and contents
362 $fqfn = $this->repairFQFN($this->getLastFile(), $uniqueID);
363 $contents = $this->repairContents($this->getLastContents(), $fqfn);
365 // Let's decompress it. First we need the instance
366 $compressInstance = $this->getCompressorChannel();
368 // Is the compressor's extension the same as the one from the data?
369 if ($compressInstance->getCompressorExtension() != $contents['header'][0]) {
371 * @todo For now we abort here but later we need to make this a little more dynamic.
373 throw new MismatchingCompressorsException(array($this, $contents['header'][0], $fqfn, $compressInstance->getCompressorExtension()), self::EXCEPTION_MISMATCHING_COMPRESSORS);
376 // Decompress the data now
377 $serialized = $compressInstance->getCompressor()->decompressStream($contents['data']);
379 // And unserialize it...
380 $object = unserialize($serialized);
382 // This must become a valid object, so let's check it...
383 if (is_null($object)) {
384 // Is null, throw exception
385 throw new NullPointerException($object, self::EXCEPTION_IS_NULL_POINTER);
386 } elseif (!is_object($object)) {
387 // Is not an object, throw exception
388 throw new NoObjectException($object, self::EXCEPTION_IS_NO_OBJECT);
389 } elseif (!method_exists($object, '__toString')) {
390 // A highly required method was not found... :-(
391 throw new MissingMethodException(array($object, '__toString'), self::EXCEPTION_MISSING_METHOD);
394 // And return the object
399 * Private method for re-gathering (repairing) the FQFN
401 * @param $fqfn The current FQFN we shall validate
402 * @param $uniqueID The unique ID number
403 * @return $fqfn The repaired FQFN when it is empty
404 * @throws NoArrayCreatedException If explode() has not
406 * @throws InvalidArrayCountException If the array count is not
409 private function repairFQFN ($fqfn, $uniqueID) {
411 $fqfn = (string) $fqfn;
412 $uniqueID = (string) $uniqueID;
414 // Is there pre-cached data available?
416 // Split the unique ID up in path and file name
417 $pathFile = explode("@", $uniqueID);
419 // Are there two elements? Index 0 is the path, 1 the file name + global extension
420 if (!is_array($pathFile)) {
422 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
423 } elseif (count($pathFile) != 2) {
424 // Invalid ID returned!
425 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
428 // Create full path name
429 $pathName = $this->getSavePath() . $pathFile[0];
431 // Nothing cached, so let's create a FQFN first
432 $fqfn = sprintf("%s/%s.%s", $pathName, $pathFile[1], $this->getFileExtension());
433 $this->setLastFile($fqfn);
436 // Return repaired FQFN
441 * Private method for re-gathering the contents of a given file
443 * @param $contents The (maybe) already cached contents as an array
444 * @param $fqfn The current FQFN we shall validate
445 * @return $contents The repaired contents from the given file
447 private function repairContents ($contents, $fqfn) {
448 // Is there some content and header (2 indexes) in?
449 if ((!is_array($contents)) || (count($contents) != 2) || (!isset($contents['header'])) || (!isset($contents['data']))) {
450 // No content found so load the file again
451 $contents = $inputHandler->loadFileContents($fqfn);
453 // And remember all data for later usage
454 $this->setLastContents($contents);
457 // Return the repaired contents
461 /* DUMMY */ public final function loadObject () {}