3 namespace Org\Mxchange\CoreFramework\Stack\File;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Factory\Stack\File\FileStackIndexFactory;
7 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
8 use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
9 use Org\Mxchange\CoreFramework\Filesystem\File\BinaryFile;
10 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
11 use Org\Mxchange\CoreFramework\Stack\BaseStacker;
12 use Org\Mxchange\CoreFramework\Traits\Index\IndexableTrait;
13 use Org\Mxchange\CoreFramework\Traits\Iterator\IteratorTrait;
14 use Org\Mxchange\CoreFramework\Utils\String\StringUtils;
17 use \InvalidArgumentException;
19 use \UnexpectedValueException;
22 * A general file-based stack class
24 * @author Roland Haeder <webmaster@ship-simu.org>
26 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2021 Core Developer Team
27 * @license GNU GPL 3.0 or any newer version
28 * @link http://www.ship-simu.org
30 * This program is free software: you can redistribute it and/or modify
31 * it under the terms of the GNU General Public License as published by
32 * the Free Software Foundation, either version 3 of the License, or
33 * (at your option) any later version.
35 * This program is distributed in the hope that it will be useful,
36 * but WITHOUT ANY WARRANTY; without even the implied warranty of
37 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
38 * GNU General Public License for more details.
40 * You should have received a copy of the GNU General Public License
41 * along with this program. If not, see <http://www.gnu.org/licenses/>.
43 abstract class BaseFileStack extends BaseStacker {
49 const EXCEPTION_BAD_MAGIC = 0xe100;
52 * Minimum block length
54 private static $minimumBlockLength = 0;
57 * Protected constructor
59 * @param $className Name of the class
62 protected function __construct (string $className) {
63 // Call parent constructor
64 parent::__construct($className);
68 * Reads the file header
71 * @todo To hard assertions here, better rewrite them to exceptions
72 * @throws UnexpectedValueException If header is not proper length
73 * @throws InvalidMagicException If a bad magic was found
75 public function readStackHeader () {
76 // First rewind to beginning as the header sits at the beginning ...
77 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
78 $this->getIteratorInstance()->rewind();
81 $headerSize = $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize();
83 // Then read it (see constructor for calculation)
84 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: headerSize=%d', $headerSize));
85 $data = $this->getIteratorInstance()->getBinaryFileInstance()->read($headerSize);
87 // Have all requested bytes been read?
88 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Read %d bytes (%d wanted).', strlen($data), $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()));
89 if (strlen($data) != $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()) {
91 throw new UnexpectedValueException(sprintf('data(%d)=%s does not match iteratorInstance->headerSize=%d',
94 $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()
96 } elseif (empty(trim($data, chr(0)))) {
97 // Empty header, file is freshly pre-allocated
98 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Empty file header detected - EXIT!');
102 // Last character must be the separator
103 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: data(-1)=%s', dechex(ord(substr($data, -1, 1)))));
104 if (substr($data, -1, 1) !== chr(BinaryFile::SEPARATOR_HEADER_ENTRIES)) {
105 // Not valid separator
106 throw new UnexpectedValueException(sprintf('data=%s does not have separator=%s at the end.',
108 BinaryFile::SEPARATOR_HEADER_ENTRIES
112 // Okay, then remove it
113 $data = substr($data, 0, -1);
115 // And update seek position
116 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Calling this->iteratorInstance->updateSeekPosition() ...');
117 $this->getIteratorInstance()->getBinaryFileInstance()->updateSeekPosition();
124 * 2 => current seek position
126 $header = explode(chr(BinaryFile::SEPARATOR_HEADER_DATA), $data);
128 // Check if the array has only 3 elements
129 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: header(%d)=%s', count($header), print_r($header, true)));
130 if (count($header) != 3) {
131 // Header array count is not expected
132 throw new UnexpectedValueException(sprintf('data=%s has %d elements, expected 3',
136 } elseif ($header[0] != StackableFile::STACK_MAGIC) {
138 throw new InvalidMagicException($data, self::EXCEPTION_BAD_MAGIC);
141 // Check length of count and seek position
142 if (strlen($header[1]) != BinaryFile::LENGTH_COUNT) {
143 // Count length not valid
144 throw new UnexpectedValueException(sprintf('header[1](%d)=%s is not expected %d length',
147 BinaryFile::LENGTH_COUNT
149 } elseif (strlen($header[1]) != BinaryFile::LENGTH_POSITION) {
150 // Position length not valid
151 throw new UnexpectedValueException(sprintf('header[2](%d)=%s is not expected %d length',
154 BinaryFile::LENGTH_POSITION
158 // Decode count and seek position
159 $header[1] = hex2bin($header[1]);
160 $header[2] = hex2bin($header[2]);
163 $this->getIteratorInstance()->getBinaryFileInstance()->setHeader($header);
166 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: EXIT!');
170 * Flushes the file header
174 public function flushFileHeader () {
175 // Put all informations together
176 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
177 $header = sprintf('%s%s%s%s%s%s',
179 StackableFile::STACK_MAGIC,
181 // Separator magic<->count
182 chr(BinaryFile::SEPARATOR_HEADER_DATA),
184 // Padded total entries
185 str_pad(StringUtils::dec2hex($this->getIteratorInstance()->getBinaryFileInstance()->getCounter()), BinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
187 // Separator count<->seek position
188 chr(BinaryFile::SEPARATOR_HEADER_DATA),
190 // Padded seek position
191 str_pad(StringUtils::dec2hex($this->getIteratorInstance()->getBinaryFileInstance()->getSeekPosition(), 2), BinaryFile::LENGTH_POSITION, '0', STR_PAD_LEFT),
193 // Separator position<->entries
194 chr(BinaryFile::SEPARATOR_HEADER_ENTRIES)
197 // Write it to disk (header is always at seek position 0)
198 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Calling this->iteratorInstance->writeAtPosition(0, header=%s) ...', $header));
199 $this->getIteratorInstance()->getBinaryFileInstance()->writeAtPosition(0, $header);
202 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: EXIT!');
206 * Initializes this file-based stack.
208 * @param $fileInfoInstance An instance of a SplFileInfo class
209 * @param $type Type of this stack (e.g. url_source for URL sources)
211 * @throws InvalidArgumentException If a parameter is invalid
212 * @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.
214 protected function initFileStack (SplFileInfo $fileInfoInstance, string $type) {
215 // Validate parameter
216 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: fileInfoInstance[%s]=%s,type=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance, $type));
219 throw new InvalidArgumentException('Parameter "type" is empty');
222 // Get a stack file instance
223 $stackInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileInfoInstance, $this));
225 // Get iterator instance
226 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($stackInstance));
229 $this->setIteratorInstance($iteratorInstance);
231 // Calculate header size
233 strlen(StackableFile::STACK_MAGIC) +
234 strlen(chr(BinaryFile::SEPARATOR_HEADER_DATA)) +
235 BinaryFile::LENGTH_COUNT +
236 strlen(chr(BinaryFile::SEPARATOR_HEADER_DATA)) +
237 BinaryFile::LENGTH_POSITION +
238 strlen(chr(BinaryFile::SEPARATOR_HEADER_ENTRIES))
242 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Setting headerSize=%d ...', $headerSize));
243 $this->getIteratorInstance()->getBinaryFileInstance()->setHeaderSize($headerSize);
245 // Init counters and gaps array
246 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Calling this->iteratorInstance->initCountersGapsArray() ...');
247 $this->getIteratorInstance()->getBinaryFileInstance()->initCountersGapsArray();
250 * Get stack index instance. This can be used for faster
251 * "defragmentation" and startup.
253 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Creating index instance for fileInfoInstance[%s]=%s,type=%s ...', get_class($fileInfoInstance), $fileInfoInstance, $type));
254 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileInfoInstance, $type);
257 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: indexInstance=%s', $indexInstance->__toString()));
258 $this->setIndexInstance($indexInstance);
260 // Is the file's header initialized?
261 if (!$this->getIteratorInstance()->getBinaryFileInstance()->isFileHeaderInitialized()) {
262 // First pre-allocate a bit
263 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Calling this->iteratorInstance->preAllocateFile(file_stack) ...');
264 $this->getIteratorInstance()->getBinaryFileInstance()->preAllocateFile('file_stack');
266 // Then create file header
267 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: this->iteratorInstance->createFileHeader() ...');
268 $this->getIteratorInstance()->getBinaryFileInstance()->createFileHeader();
271 // Load the file header
272 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Calling this->readStackHeader() ...');
273 $this->readStackHeader();
275 // Is the index loaded correctly and the stack file is just created?
276 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Calling this->indexInstance->isIndexLoaded() ...');
277 if (!$this->getIndexInstance()->isIndexLoaded()) {
279 * Something horrible has happened to the index as it should be
280 * loaded at this point. The stack's file structure then needs to
281 * be analyzed and the index rebuild.
283 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Calling this->iteratorInstance->analyzeFileStructure() ...');
284 $this->getIteratorInstance()->getBinaryFileInstance()->analyzeFileStructure();
286 // Rebuild index from file
287 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Calling this->iteratorInstance->rebuildIndexFromStack(%s) ...', $this->__toString()));
288 $this->getIndexInstance()->rebuildIndexFromStack($this);
292 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: EXIT!');
296 * Adds a value to given stack
298 * @param $stackerName Name of the stack
299 * @param $value Value to add to this stacker
301 * @throws FullStackerException If the stack is full
302 * @throws InvalidArgumentException If a parameter is not valid
303 * @throws InvalidArgumentException Not all variable types are wanted here
305 protected function addValueToStack (string $stackerName, $value) {
306 // Validate parameter
307 /* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s,value[]=%s - CALLED!', $stackerName, gettype($value)));
308 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s,value[%s]=%s', $stackerName, gettype($value), print_r($value, true)));
309 if (empty($stackerName)) {
310 // No empty stack name
311 throw new InvalidArgumentException('Parameter "stackerName" is empty');
312 } elseif ($this->isStackFull($stackerName)) {
314 throw new FullStackerException([$this, $stackerName, $value], self::EXCEPTION_STACKER_IS_FULL);
315 } elseif (is_resource($value) || is_object($value)) {
317 throw new InvalidArgumentException(sprintf('value[]=%s is not supported', gettype($value)));
321 * Now add the value to the file stack which returns gap position, a
322 * hash and length of the raw data.
324 $data = $this->getIteratorInstance()->getBinaryFileInstance()->writeValueToFile($stackerName, $value);
326 // Add the hash and gap position to the index
327 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: data=%s', print_r($data, true));
328 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Calling this->indexInstance->addHashedDataToIndex(%s,data()=%d) ...', $stackerName, count($data)));
329 $this->getIndexInstance()->addHashedDataToIndex($stackerName, $data);
332 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: EXIT!');
336 * Get last value from named stacker
338 * @param $stackerName Name of the stack
339 * @return $value Value of last added value
340 * @throws InvalidArgumentException If a parameter is not valid
341 * @throws BadMethodCallException If the stack is empty
343 protected function getLastValue (string $stackerName) {
344 // Validate parameter
345 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
346 if (empty($stackerName)) {
347 // No empty stack name
348 throw new InvalidArgumentException('Parameter "stackerName" is empty');
349 } elseif ($this->isStackEmpty($stackerName)) {
350 // Throw an exception
351 throw new BadMethodCallException([$this, $stackerName], self::EXCEPTION_STACKER_IS_EMPTY);
354 // Now get the last value
355 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
359 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: value[]=%s - EXIT!', gettype($value)));
364 * Get first value from named stacker
366 * @param $stackerName Name of the stack
367 * @return $value Value of last added value
368 * @throws InvalidArgumentException If a parameter is not valid
369 * @throws BadMethodCallException If the stack is empty
371 protected function getFirstValue (string $stackerName) {
372 // Validate parameter
373 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
374 if (empty($stackerName)) {
375 // No empty stack name
376 throw new InvalidArgumentException('Parameter "stackerName" is empty');
377 } elseif ($this->isStackEmpty($stackerName)) {
378 // Throw an exception
379 throw new BadMethodCallException([$this, $stackerName], self::EXCEPTION_STACKER_IS_EMPTY);
382 // Now get the first value
383 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
387 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: value[]=%s - EXIT!', gettype($value)));
392 * "Pops" last entry from stack
394 * @param $stackerName Name of the stack
395 * @return $value Value "poped" from array
396 * @throws InvalidArgumentException If a parameter is not valid
397 * @throws BadMethodCallException If the stack is empty
399 protected function popLast (string $stackerName) {
400 // Validate parameter
401 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
402 if (empty($stackerName)) {
403 // No empty stack name
404 throw new InvalidArgumentException('Parameter "stackerName" is empty');
405 } elseif ($this->isStackEmpty($stackerName)) {
406 // Throw an exception
407 throw new BadMethodCallException([$this, $stackerName], self::EXCEPTION_STACKER_IS_EMPTY);
410 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
411 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
416 * "Pops" first entry from stack
418 * @param $stackerName Name of the stack
419 * @return $value Value "shifted" from array
420 * @throws InvalidArgumentException If a parameter is not valid
421 * @throws BadMethodCallException If the named stacker is empty
423 protected function popFirst (string $stackerName) {
424 // Validate parameter
425 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
426 if (empty($stackerName)) {
427 // No empty stack name
428 throw new InvalidArgumentException('Parameter "stackerName" is empty');
429 } elseif ($this->isStackEmpty($stackerName)) {
430 // Throw an exception
431 throw new BadMethodCallException([$this, $stackerName], self::EXCEPTION_STACKER_IS_EMPTY);
434 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
435 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
440 * Checks whether the given stack is full
442 * @param $stackerName Name of the stack
443 * @return $isFull Whether the stack is full
444 * @throws InvalidArgumentException If a parameter is not valid
446 protected function isStackFull (string $stackerName) {
447 // Validate parameter
448 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
449 if (empty($stackerName)) {
450 // No empty stack name
451 throw new InvalidArgumentException('Parameter "stackerName" is empty');
454 // @TODO Please implement this, returning false
455 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
459 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: isFull=%d - EXIT!', intval($isFull)));
464 * Checks whether the given stack is empty
466 * @param $stackerName Name of the stack
467 * @return $isEmpty Whether the stack is empty
468 * @throws InvalidArgumentException If a parameter is not valid
469 * @throws BadMethodCallException If given stack is missing
471 public function isStackEmpty (string $stackerName) {
472 // Validate parameter
473 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
474 if (empty($stackerName)) {
475 // No empty stack name
476 throw new InvalidArgumentException('Parameter "stackerName" is empty');
479 // So, is the stack empty?
480 $isEmpty = (($this->getStackCount($stackerName)) == 0);
483 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: isEmpty=%d - EXIT!', intval($isEmpty)));
488 * Checks whether the given stack is initialized (set in array $stackers)
490 * @param $stackerName Name of the stack
491 * @return $isInitialized Whether the stack is initialized
492 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
494 public function isStackInitialized (string $stackerName) {
495 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
499 * Determines whether the EOF has been reached
501 * @return $isEndOfFileReached Whether the EOF has been reached
502 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
504 public function isEndOfFileReached () {
505 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
509 * Getter for size of given stack (array count)
511 * @param $stackerName Name of the stack
512 * @return $count Size of stack (array count)
514 public function getStackCount (string $stackerName) {
515 // Now, simply return the found count value, this must be up-to-date then!
516 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
517 $count = $this->getIteratorInstance()->getBinaryFileInstance()->getCounter();
520 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: count=%d - EXIT!', $count));
525 * Calculates minimum length for one entry/block
527 * @return $length Minimum length for one entry/block
529 public function calculateMinimumBlockLength () {
530 // Is the value "cached"?
531 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
532 if (self::$minimumBlockLength == 0) {
534 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Calculating ...');
535 self::$minimumBlockLength =
536 // Length of entry group
537 BinaryFile::LENGTH_GROUP + strlen(chr(BinaryFile::SEPARATOR_GROUP_HASH)) +
539 self::getHashLength() + strlen(chr(BinaryFile::SEPARATOR_HASH_VALUE)) + 1 +
541 strlen(chr(BinaryFile::SEPARATOR_ENTRIES));
545 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: self::minimumBlockLength=%d - EXIT!', self::$minimumBlockLength));
546 return self::$minimumBlockLength;
550 * Initializes counter for valid entries, arrays for damaged entries and
551 * an array for gap seek positions. If you call this method on your own,
552 * please re-analyze the file structure. So you are better to call
553 * analyzeFileStructure() instead of this method.
556 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
558 public function initCountersGapsArray () {
559 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
563 * Getter for header size
565 * @return $totalEntries Size of file header
566 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
568 public final function getHeaderSize () {
569 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
573 * Setter for header size
575 * @param $headerSize Size of file header
577 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
579 public final function setHeaderSize (int $headerSize) {
580 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
584 * Getter for header array
586 * @return $totalEntries Size of file header
587 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
589 public final function getHeader () {
590 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
596 * @param $header Array for a file header
598 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
600 public final function setHeader (array $header) {
601 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
605 * Updates seekPosition attribute from file to avoid to much access on file.
608 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
610 public function updateSeekPosition () {
611 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
615 * Getter for total entries
617 * @return $totalEntries Total entries in this file
618 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
620 public final function getCounter () {
621 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
625 * Writes data at given position
627 * @param $seekPosition Seek position
628 * @param $data Data to be written
629 * @param $flushHeader Whether to flush the header (default: flush)
631 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
633 public function writeData (int $seekPosition, string $data, bool $flushHeader = true) {
635 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
639 * Writes at given position by seeking to it.
641 * @param $seekPosition Seek position in file
642 * @param $dataStream Data to be written
643 * @return mixed Number of writes bytes or false on error
644 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
646 public function writeAtPosition (int $seekPosition, string $dataStream) {
648 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
652 * Writes given value to the file and returns a hash and gap position for it
654 * @param $stackName Group identifier
655 * @param $value Value to be added to the stack
656 * @return $data Hash and gap position
657 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
659 public function writeValueToFile (string $stackName, $value) {
660 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
664 * Searches for next suitable gap the given length of data can fit in
665 * including padding bytes.
667 * @param $length Length of raw data
668 * @return $seekPosition Found next gap's seek position
669 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
671 public function searchNextGap (int $length) {
672 // Not supported here
673 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
677 * "Getter" for file size
679 * @return $fileSize Size of currently loaded file
681 public function getFileSize () {
682 // Call iterator's method
683 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
684 $size = $this->getIteratorInstance()->getBinaryFileInstance()->getFileSize();
687 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: size=%d - EXIT!', $size));
692 * Writes given raw data to the file and returns a gap position and length
694 * @param $stackName Group identifier
695 * @param $hash Hash from encoded value
696 * @param $encoded Encoded value to be written to the file
697 * @return $data Gap position and length of the raw data
699 public function writeDataToFreeGap (string $stackName, string $hash, string $encoded) {
700 // Raw data been written to the file
701 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackName=%s,hash=%s,encoded()=%d - CALLED!', $stackName, $hash, strlen($encoded)));
702 $rawData = sprintf('%s%s%s%s%s',
704 BinaryFile::SEPARATOR_GROUP_HASH,
706 BinaryFile::SEPARATOR_HASH_VALUE,
710 // Search for next free gap
711 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackName=%s,hash=%s,rawData()=%d', $stackName, $hash, strlen($rawData)));
712 $gapPosition = $this->getIteratorInstance()->getBinaryFileInstance()->searchNextGap(strlen($rawData));
714 // Gap position cannot be smaller than header length + 1
715 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: gapPosition=%d', $gapPosition));
716 if ($gapPosition <= $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()) {
717 // Improper gap position
718 throw new UnexpectedValueException(sprintf('gapPosition[%s]=%d is not larger than headerSize=%d',
719 gettype($gapPosition),
721 $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()
725 // Then write the data at that gap
726 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackName=%s,hash=%s,gapPosition=%s', $stackName, $hash, $gapPosition));
727 $this->getIteratorInstance()->getBinaryFileInstance()->writeData($gapPosition, $rawData);
729 // Return gap position, hash and length of raw data
730 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackName=%s,hash=%s,rawData()=%d - EXIT!', $stackName, $hash, strlen($rawData)));
732 StackableFile::ARRAY_NAME_GAP_POSITION => $gapPosition,
733 StackableFile::ARRAY_NAME_HASH => $hash,
734 StackableFile::ARRAY_NAME_DATA_LENGTH => strlen($rawData),