3 * A general file-based stack class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2013 Core Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class BaseFileStack extends BaseStacker {
26 * Magic for this stack
28 const STACK_MAGIC = 'STACKv0.1';
31 * Protected constructor
33 * @param $className Name of the class
36 protected function __construct ($className) {
37 // Call parent constructor
38 parent::__construct($className);
42 * Reads the file header
45 * @todo To hard assertions here, better rewrite them to exceptions
47 public function readFileHeader () {
48 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
50 // First rewind to beginning as the header sits at the beginning ...
51 $this->getIteratorInstance()->rewind();
53 // Then read it (see constructor for calculation)
54 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
55 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
57 // Have all requested bytes been read?
58 assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
59 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
61 // Last character must be the separator
62 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
63 assert(substr($data, -1, 1) == chr(BaseFile::SEPARATOR_HEADER_ENTRIES));
64 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
66 // Okay, then remove it
67 $data = substr($data, 0, -1);
69 // And update seek position
70 $this->getIteratorInstance()->updateSeekPosition();
77 * 2 => current seek position
79 $header = explode(chr(BaseFile::SEPARATOR_HEADER_DATA), $data);
82 $this->getIteratorInstance()->setHeader($header);
84 // Check if the array has only 3 elements
85 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, TRUE)));
86 assert(count($header) == 3);
87 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
90 assert($header[0] == self::STACK_MAGIC);
91 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
93 // Check length of count and seek position
94 assert(strlen($header[1]) == BaseFile::LENGTH_COUNT);
95 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
96 assert(strlen($header[2]) == BaseFile::LENGTH_POSITION);
97 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
99 // Decode count and seek position
100 $header[1] = hex2bin($header[1]);
101 $header[2] = hex2bin($header[2]);
103 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
107 * Flushes the file header
111 public function flushFileHeader () {
112 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
114 // Put all informations together
115 $header = sprintf('%s%s%s%s%s%s',
119 // Separator magic<->count
120 chr(BaseFile::SEPARATOR_HEADER_DATA),
122 // Total entries (will be zero) and pad it to 20 chars
123 str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
125 // Separator count<->seek position
126 chr(BaseFile::SEPARATOR_HEADER_DATA),
128 // Position (will be zero)
129 str_pad($this->dec2hex($this->getSeekPosition(), 2), BaseFile::LENGTH_POSITION, '0', STR_PAD_LEFT),
131 // Separator position<->entries
132 chr(BaseFile::SEPARATOR_HEADER_ENTRIES)
135 // Write it to disk (header is always at seek position 0)
136 $this->writeData(0, $header, FALSE);
138 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
142 * Initializes this file-based stack.
144 * @param $fileName File name of this stack
145 * @param $type Type of this stack (e.g. url_source for URL sources)
147 * @todo Currently the stack file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole stack file.
149 protected function initFileStack ($fileName, $type) {
150 // Get a stack file instance
151 $fileInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileName, $this));
153 // Get iterator instance
154 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
156 // Is the instance implementing the right interface?
157 assert($iteratorInstance instanceof SeekableWritableFileIterator);
160 $this->setIteratorInstance($iteratorInstance);
162 // Calculate header size
163 $this->getIteratorInstance()->setHeaderSize(
164 strlen(self::STACK_MAGIC) +
165 strlen(chr(BaseFile::SEPARATOR_HEADER_DATA)) +
166 BaseFile::LENGTH_COUNT +
167 strlen(chr(BaseFile::SEPARATOR_HEADER_DATA)) +
168 BaseFile::LENGTH_POSITION +
169 strlen(chr(BaseFile::SEPARATOR_HEADER_ENTRIES))
172 // Init counters and gaps array
173 $this->getIteratorInstance()->initCountersGapsArray();
175 // Is the file's header initialized?
176 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
177 // No, then create it (which may pre-allocate the stack)
178 $this->getIteratorInstance()->createFileHeader();
180 // And pre-allocate a bit
181 $this->getIteratorInstance()->preAllocateFile('file_stack');
184 // Load the file header
185 $this->readFileHeader();
187 // Count all entries in file
188 $this->getIteratorInstance()->analyzeFile();
191 * Get stack index instance. This can be used for faster
192 * "defragmentation" and startup.
194 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileName, $type);
197 $this->setIndexInstance($indexInstance);
201 * Adds a value to given stack
203 * @param $stackerName Name of the stack
204 * @param $value Value to add to this stacker
206 * @throws FullStackerException If the stack is full
208 protected function addValue ($stackerName, $value) {
210 if ($this->isStackFull($stackerName)) {
212 throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
215 // Now add the value to the stack
216 $this->partialStub('stackerName=' . $stackerName . ',value[]=' . gettype($value));
220 * Get last value from named stacker
222 * @param $stackerName Name of the stack
223 * @return $value Value of last added value
224 * @throws EmptyStackerException If the stack is empty
226 protected function getLastValue ($stackerName) {
227 // Is the stack not yet initialized or full?
228 if ($this->isStackEmpty($stackerName)) {
229 // Throw an exception
230 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
233 // Now get the last value
234 $this->partialStub('stackerName=' . $stackerName);
242 * Get first value from named stacker
244 * @param $stackerName Name of the stack
245 * @return $value Value of last added value
246 * @throws EmptyStackerException If the stack is empty
248 protected function getFirstValue ($stackerName) {
249 // Is the stack not yet initialized or full?
250 if ($this->isStackEmpty($stackerName)) {
251 // Throw an exception
252 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
255 // Now get the first value
256 $this->partialStub('stackerName=' . $stackerName);
264 * "Pops" last entry from stack
266 * @param $stackerName Name of the stack
267 * @return $value Value "poped" from array
268 * @throws EmptyStackerException If the stack is empty
270 protected function popLast ($stackerName) {
271 // Is the stack not yet initialized or full?
272 if ($this->isStackEmpty($stackerName)) {
273 // Throw an exception
274 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
277 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
278 $this->partialStub('stackerName=' . $stackerName);
283 * "Pops" first entry from stack
285 * @param $stackerName Name of the stack
286 * @return $value Value "shifted" from array
287 * @throws EmptyStackerException If the named stacker is empty
289 protected function popFirst ($stackerName) {
290 // Is the stack not yet initialized or full?
291 if ($this->isStackEmpty($stackerName)) {
292 // Throw an exception
293 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
296 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
297 $this->partialStub('stackerName=' . $stackerName);
302 * Checks whether the given stack is full
304 * @param $stackerName Name of the stack
305 * @return $isFull Whether the stack is full
307 protected function isStackFull ($stackerName) {
308 // File-based stacks will only run full if the disk space is low.
309 // @TODO Please implement this, returning FALSE
317 * Checks whether the given stack is empty
319 * @param $stackerName Name of the stack
320 * @return $isEmpty Whether the stack is empty
321 * @throws NoStackerException If given stack is missing
323 public function isStackEmpty ($stackerName) {
324 // So, is the stack empty?
325 $isEmpty = (($this->getStackCount($stackerName)) == 0);
332 * Initializes given stacker
334 * @param $stackerName Name of the stack
335 * @param $forceReInit Force re-initialization
337 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
339 public function initStack ($stackerName, $forceReInit = FALSE) {
340 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
344 * Initializes all stacks
347 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
349 public function initStacks (array $stacks, $forceReInit = FALSE) {
350 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
354 * Checks whether the given stack is initialized (set in array $stackers)
356 * @param $stackerName Name of the stack
357 * @return $isInitialized Whether the stack is initialized
358 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
360 public function isStackInitialized ($stackerName) {
361 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
365 * Close a file source and set it's instance to null and the file name
369 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
371 public function closeFile () {
372 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
376 * Determines whether the EOF has been reached
378 * @return $isEndOfFileReached Whether the EOF has been reached
379 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
381 public function isEndOfFileReached () {
382 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
386 * Getter for file name
388 * @return $fileName The current file name
389 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
391 public function getFileName () {
392 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
396 * Getter for size of given stack (array count)
398 * @param $stackerName Name of the stack
399 * @return $count Size of stack (array count)
401 public function getStackCount ($stackerName) {
402 // Now, simply return the found count value, this must be up-to-date then!
403 return $this->getIteratorInstance()->getCounter();
407 * Calculates minimum length for one entry/block
409 * @return $length Minimum length for one entry/block
411 public function calculateMinimumBlockLength () {
413 $length = self::getHashLength() + strlen(chr(BaseFile::SEPARATOR_HASH_NAME)) + BaseFile::LENGTH_NAME + 1 + strlen(chr(BaseFile::SEPARATOR_ENTRIES));
420 * Initializes counter for valid entries, arrays for damaged entries and
421 * an array for gap seek positions. If you call this method on your own,
422 * please re-analyze the file structure. So you are better to call
423 * analyzeFile() instead of this method.
426 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
428 public function initCountersGapsArray () {
429 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
433 * Getter for header size
435 * @return $totalEntries Size of file header
436 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
438 public final function getHeaderSize () {
439 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
443 * Setter for header size
445 * @param $headerSize Size of file header
447 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
449 public final function setHeaderSize ($headerSize) {
450 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
454 * Getter for header array
456 * @return $totalEntries Size of file header
457 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
459 public final function getHeader () {
460 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
466 * @param $header Array for a file header
468 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
470 public final function setHeader (array $header) {
471 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
475 * Updates seekPosition attribute from file to avoid to much access on file.
478 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
480 public function updateSeekPosition () {
481 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
485 * Getter for total entries
487 * @return $totalEntries Total entries in this file
488 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
490 public final function getCounter () {
491 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
495 * "Getter" for file size
497 * @return $fileSize Size of currently loaded file
499 public function getFileSize () {
500 // Call iterator's method
501 return $this->getIteratorInstance()->getFileSize();