3 namespace Org\Mxchange\CoreFramework\Filesystem\File;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
8 use Org\Mxchange\CoreFramework\Filesystem\Block;
9 use Org\Mxchange\CoreFramework\Filesystem\Block\CalculatableBlock;
10 use Org\Mxchange\CoreFramework\Filesystem\File\BaseAbstractFile;
13 use \BadMethodCallException;
14 use \InvalidArgumentException;
18 * A general binary file class
20 * @author Roland Haeder <webmaster@ship-simu.org>
22 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
23 * @license GNU GPL 3.0 or any newer version
24 * @link http://www.ship-simu.org
26 * This program is free software: you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as published by
28 * the Free Software Foundation, either version 3 of the License, or
29 * (at your option) any later version.
31 * This program is distributed in the hope that it will be useful,
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
36 * You should have received a copy of the GNU General Public License
37 * along with this program. If not, see <http://www.gnu.org/licenses/>.
39 abstract class BaseBinaryFile extends BaseAbstractFile {
41 * Separator for header data
43 const SEPARATOR_HEADER_DATA = 0x01;
46 * Separator header->entries
48 const SEPARATOR_HEADER_ENTRIES = 0x02;
51 * Separator group->hash
53 const SEPARATOR_GROUP_HASH = 0x03;
56 * Separator hash->value
58 const SEPARATOR_HASH_VALUE = 0x04;
61 * Separator entry->entry
63 const SEPARATOR_ENTRIES = 0x05;
66 * Separator type->position
68 const SEPARATOR_TYPE_POSITION = 0x06;
73 const LENGTH_COUNT = 20;
78 const LENGTH_POSITION = 20;
83 const LENGTH_GROUP = 10;
86 * Maximum length of entry type
88 const LENGTH_TYPE = 20;
90 //***** Array elements for 'gaps' array *****
95 const GAPS_INDEX_START = 'start';
100 const GAPS_INDEX_END = 'end';
103 * Current seek position
105 private $seekPosition = 0;
110 private $headerSize = 0;
115 private $header = [];
118 * Seek positions for gaps ("fragmentation")
123 * Seek positions for damaged entries (e.g. mismatching hash sum, ...)
125 private $damagedEntries = [];
130 private $backBuffer = '';
133 * Currently loaded block (will be returned by current())
135 private $currentBlock = '';
138 * An instance of a Block class
140 private $blockInstance = NULL;
143 * Protected constructor
145 * @param $className Name of the class
148 protected function __construct (string $className) {
149 // Call parent constructor
150 parent::__construct($className);
152 // Init counters and gaps array
153 $this->initCountersGapsArray();
157 * Setter for Block instance
159 * @param $blockInstance An instance of an Block class
162 protected final function setBlockInstance (Block $blockInstance) {
163 $this->blockInstance = $blockInstance;
167 * Getter for Block instance
169 * @return $blockInstance An instance of an Block class
171 public final function getBlockInstance () {
172 return $this->blockInstance;
176 * Checks whether the abstracted file only contains gaps by counting all
177 * gaps' bytes together and compare it to total length.
179 * @return $isGapsOnly Whether the abstracted file only contains gaps
181 private function isFileOnlyGaps () {
182 // First/last gap found?
183 /* Only for debugging
184 if (isset($this->gaps[0])) {
185 // Output first and last gap
186 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] this->gaps[0]=%s,this->gaps[%s]=%s', print_r($this->gaps[0], true), (count($this->gaps) - 1), print_r($this->gaps[count($this->gaps) - 1], true)));
190 // Now count every gap
192 foreach ($this->gaps as $gap) {
193 // Calculate size of found gap: end-start including both
194 $gapsSize += ($gap[self::GAPS_INDEX_END] - $gap[self::GAPS_INDEX_START]);
198 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] gapsSize=%s,this->headerSize=%s', $gapsSize, $this->getHeaderSize()));
200 // Total gap size + header size must be same as file size
201 $isGapsOnly = (($this->getHeaderSize() + $gapsSize) == $this->getFileSize());
208 * Initializes counter for valid entries, arrays for damaged entries and
209 * an array for gap seek positions. If you call this method on your own,
210 * please re-analyze the file structure. So you are better to call
211 * analyzeFile() instead of this method.
215 public function initCountersGapsArray () {
216 // Init counter and seek position
217 $this->setCounter(0);
218 $this->setSeekPosition(0);
222 $this->damagedEntries = [];
226 * Getter for header size
228 * @return $totalEntries Size of file header
230 public final function getHeaderSize () {
232 return $this->headerSize;
236 * Setter for header size
238 * @param $headerSize Size of file header
241 public final function setHeaderSize (int $headerSize) {
243 $this->headerSize = $headerSize;
247 * Getter for header array
249 * @return $totalEntries Size of file header
251 public final function getHeader () {
253 return $this->header;
259 * @param $header Array for a file header
262 public final function setHeader (array $header) {
264 $this->header = $header;
268 * Getter for seek position
270 * @return $seekPosition Current seek position (stored here in object)
272 public final function getSeekPosition () {
274 return $this->seekPosition;
278 * Setter for seek position
280 * @param $seekPosition Current seek position (stored here in object)
283 protected final function setSeekPosition (int $seekPosition) {
285 $this->seekPosition = $seekPosition;
289 * Updates seekPosition attribute from file to avoid to much access on file.
293 public function updateSeekPosition () {
294 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!'));
296 // Get key (= seek position)
297 $seekPosition = $this->key();
298 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Setting seekPosition=%s', $seekPosition));
301 $this->setSeekPosition($seekPosition);
303 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!'));
307 * Seeks to beginning of file, updates seek position in this object and
308 * flushes the header.
312 protected function rewindUpdateSeekPosition () {
313 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!'));
315 // flushFileHeader must be callable
316 assert(is_callable(array($this, 'flushFileHeader')));
318 // Seek to beginning of file
321 // And update seek position ...
322 $this->updateSeekPosition();
324 // ... to write it back into the file
325 $this->flushFileHeader();
327 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!'));
331 * Seeks to old position
335 protected function seekToOldPosition () {
336 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!'));
338 // Seek to currently ("old") saved position
339 $this->seek($this->getSeekPosition());
341 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!'));
345 * Checks whether the block separator has been found
347 * @param $str String to look in
348 * @return $isFound Whether the block separator has been found
350 public static function isBlockSeparatorFound ($str) {
352 $isFound = (strpos($str, chr(self::SEPARATOR_ENTRIES)) !== false);
359 * Initializes the back-buffer by setting it to an empty string.
363 private function initBackBuffer () {
364 // Simply call the setter
365 $this->setBackBuffer('');
369 * Setter for backBuffer field
371 * @param $backBuffer Characters to "store" in back-buffer
374 private function setBackBuffer (string $backBuffer) {
376 $this->backBuffer = $backBuffer;
380 * Getter for backBuffer field
382 * @return $backBuffer Characters "stored" in back-buffer
384 private function getBackBuffer () {
385 return $this->backBuffer;
389 * Setter for currentBlock field
391 * @param $currentBlock Characters to set a currently loaded block
394 private function setCurrentBlock (string $currentBlock) {
396 $this->currentBlock = $currentBlock;
400 * Gets currently read data
402 * @return $current Currently read data
404 public function getCurrentBlock () {
406 return $this->currentBlock;
410 * Initializes this file class
412 * @param $fileInfoInstance An instance of a SplFileInfo class
415 protected function initFile (SplFileInfo $fileInfoInstance) {
416 // Get a file i/o pointer instance
417 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: fileInfoInstance[%s]=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance));
418 $pointerInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_output_class', array($fileInfoInstance));
420 // ... and set it here
421 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Setting pointerInstance=%s ...', $pointerInstance->__toString()));
422 $this->setPointerInstance($pointerInstance);
425 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
429 * Writes data at given position
431 * @param $seekPosition Seek position
432 * @param $data Data to be written
433 * @param $flushHeader Whether to flush the header (default: flush)
435 * @throws InvalidArgumentException If a parameter is invalid
437 public function writeData (int $seekPosition, string $data, bool $flushHeader = true) {
438 // Validate parameter
439 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%s,data()=%d,flushHeader=%d - CALLED!', $seekPosition, strlen($data), intval($flushHeader)));
440 if ($seekPosition < 0) {
441 // Invalid seek position
442 throw new InvalidArgumentException(sprintf('seekPosition=%d is not valid', $seekPosition));
443 } elseif (empty($data)) {
444 // Empty data is invalid, too
445 throw new InvalidArgumentException('Parameter "data" is empty');
448 // Write data at given position
449 $this->getPointerInstance()->writeAtPosition($seekPosition, $data);
452 $this->incrementCounter();
454 // Update seek position
455 $this->updateSeekPosition();
458 if ($flushHeader === true) {
460 $this->flushFileHeader();
462 // Seek to old position
463 $this->seekToOldPosition();
467 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
471 * Marks the currently loaded block as empty (with length of the block)
473 * @param $length Length of the block
475 * @throws InvalidArgumentException If a parameter is invalid
477 protected function markCurrentBlockAsEmpty (int $length) {
478 // Validate parameter
479 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: length=%d - CALLED!', $length));
481 // Length cannot below one
482 throw new InvalidArgumentException(sprintf('length=%d is not valid', $length));
485 // Get current seek position
486 $currentPosition = $this->key();
488 // Now add it as gap entry
489 array_push($this->gaps, array(
490 self::GAPS_INDEX_START => ($currentPosition - $length),
491 self::GAPS_INDEX_END => $currentPosition,
495 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
499 * Checks whether the file header is initialized
501 * @return $isInitialized Whether the file header is initialized
503 public function isFileHeaderInitialized () {
504 // Default is not initialized
505 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
506 $isInitialized = false;
508 // Is the file initialized?
509 if ($this->isFileInitialized()) {
510 // Some bytes has been written, so rewind to start of it.
511 $rewindStatus = $this->rewind();
513 // Is the rewind() call successfull?
514 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: rewindStatus=%d', $rewindStatus));
515 if ($rewindStatus != 1) {
516 // Something bad happened
517 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Could not rewind().');
521 $this->readFileHeader();
523 // The above method does already check the header
524 $isInitialized = true;
528 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: isInitialized=%d - EXIT!', intval($isInitialized)));
529 return $isInitialized;
533 * Checks whether the assigned file has been initialized
535 * @return $isInitialized Whether the file's size is zero
537 public function isFileInitialized () {
538 // Get it from iterator which holds the pointer instance. If false is returned
539 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
540 $fileSize = $this->size();
541 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: fileSize=%s', $fileSize));
544 * The returned file size should not be false or NULL as this means
545 * that the pointer class does not work correctly.
547 assert(is_int($fileSize));
549 // Is more than 0 returned?
550 $isInitialized = ($fileSize > 0);
553 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: isInitialized=%d - EXIT!', intval($isInitialized)));
554 return $isInitialized;
558 * Creates the assigned file
562 public function createFileHeader () {
563 // The file's header should not be initialized here
564 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
565 assert(!$this->isFileHeaderInitialized());
567 // Simple flush file header which will create it.
568 $this->flushFileHeader();
570 // Rewind seek position (to beginning of file) and update/flush file header
571 $this->rewindUpdateSeekPosition();
574 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
578 * Pre-allocates file (if enabled) with some space for later faster write access.
580 * @param $type Type of the file
582 * @throws InvalidArgumentException If a parameter is empty
584 public function preAllocateFile (string $type) {
586 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: type=%s - CALLED!', $type));
589 throw new InvalidArgumentException('Parameter "type" is empty');
590 } elseif (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($type . '_pre_allocate_enabled') != 'Y') {
591 // Don't continue here.
592 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Not pre-allocating file.'));
597 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Pre-allocating file ...');
599 // Calculate minimum length for one entry
600 $minLengthEntry = $this->getBlockInstance()->calculateMinimumBlockLength();
602 // Calulcate seek position
603 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: minLengthEntry=%s', $minLengthEntry));
604 $seekPosition = $minLengthEntry * FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($type . '_pre_allocate_count');
606 // Now simply write a NUL there. This will pre-allocate the file.
607 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%d', $seekPosition));
608 $this->writeData($seekPosition, chr(0));
610 // Rewind seek position (to beginning of file) and update/flush file header
611 $this->rewindUpdateSeekPosition();
614 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
618 * Determines seek position
620 * @return $seekPosition Current seek position
622 public function determineSeekPosition () {
623 // Call pointer instance
624 return $this->getPointerInstance()->determineSeekPosition();
628 * Seek to given offset (default) or other possibilities as fseek() gives.
630 * @param $offset Offset to seek to (or used as "base" for other seeks)
631 * @param $whence Added to offset (default: only use offset to seek to)
632 * @return $status Status of file seek: 0 = success, -1 = failed
634 public function seek (int $offset, $whence = SEEK_SET) {
635 // Call pointer instance
636 return $this->getPointerInstance()->seek($offset, $whence);
640 * Reads given amount of bytes from file.
642 * @param $bytes Amount of bytes to read
643 * @return $data Data read from file
645 public function read (int $bytes = 0) {
646 // Call pointer instance
647 return $this->getPointerInstance()->read($bytes);
651 * Rewinds to the beginning of the file
653 * @return $status Status of this operation
655 public function rewind () {
656 // Call pointer instance
657 return $this->getPointerInstance()->rewind();
661 * Analyzes entries in index file. This will count all found (and valid)
662 * entries, mark invalid as damaged and count gaps ("fragmentation"). If
663 * only gaps are found, the file is considered as "virgin" (no entries).
666 * @throws BadMethodCallException If this method is called but file is not initialized
668 public function analyzeFile () {
669 // Make sure the file is initialized
670 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
671 if (!$this->isFileInitialized()) {
673 throw new BadMethodCallException('Method called but file is not initialized.');
676 // Init counters and gaps array
677 $this->initCountersGapsArray();
679 // Output message (as this may take some time)
680 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Analyzing file structure ... (this may take some time)'));
682 // First rewind to the begining
685 // Then try to load all entries
686 while ($this->valid()) {
691 $current = $this->getCurrentBlock();
694 * If the block is empty, maybe the whole file is? This could mean
695 * that the file has been pre-allocated.
697 if (empty($current)) {
698 // Then skip this part
703 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('current()=%d', strlen($current)));
706 // If the last read block is empty, check gaps
707 if (empty($current)) {
709 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Found a total of %s gaps.', count($this->gaps)));
711 // Check gaps, if the whole file is empty.
712 if ($this->isFileOnlyGaps()) {
713 // Only gaps, so don't continue here.
718 * The above call has calculated a total size of all gaps. If the
719 * percentage of gaps passes a "soft" limit and last
720 * defragmentation is to far in the past, or if a "hard" limit has
721 * reached, run defragmentation.
723 if ($this->isDefragmentationNeeded()) {
724 // Run "defragmentation"
725 $this->doRunDefragmentation();
728 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
732 * Advances to next "block" of bytes
735 * @throws UnexpectedValueException If some unexpected value was found
737 public function next () {
738 // Is there nothing to read?
739 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
740 if (!$this->valid()) {
745 // First calculate minimum block length
746 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: key()=%d', $this->key()));
747 $length = $this->getBlockInstance()->calculateMinimumBlockLength();
748 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: length=%s', $length));
750 // Read possibly back-buffered bytes from previous call of next().
751 $data = $this->getBackBuffer();
754 * Read until a entry/block separator has been found. The next read
755 * "block" may not fit, so this loop will continue until the EOB or EOF
756 * has been reached whatever comes first.
758 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: data()=%d', strlen($data)));
759 while ((!$this->isEndOfFileReached()) && (!self::isBlockSeparatorFound($data))) {
760 // Then read the next possible block
761 $block = $this->read($length);
764 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: block()=%d,length=%s', strlen($block), $length));
765 if (strlen(trim($block)) == 0) {
766 // Mark this block as empty
767 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling markCurrentBlockAsEmpty(%d) ...', strlen($block)));
768 $this->markCurrentBlockAsEmpty(strlen($block));
770 // Skip to next block
771 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CONTINUE!');
775 // At this block then
779 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: data()=%d', strlen($data)));
783 if ($this->isEndOfFileReached()) {
784 // Set whole data as current read block
785 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling setCurrentBlock(%d) ...', strlen($data)));
786 $this->setCurrentBlock($data);
788 // Then abort here silently
789 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EOF reached - EXIT!');
794 * Init back-buffer which is the data that has been found beyond the
797 $this->initBackBuffer();
800 $dataArray = explode(chr(self::SEPARATOR_ENTRIES), $data);
802 // This array must contain two elements
803 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: dataArray=' . print_r($dataArray, true));
804 if (count($dataArray) != 2) {
806 throw new UnexpectedValueException(sprintf('dataArray()=%d is not expected, want 2', count($dataArray)));
809 // Left part is the actual block, right one the back-buffer data
810 $this->setCurrentBlock($dataArray[0]);
811 $this->setBackBuffer($dataArray[1]);
814 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
818 * Checks wether the current entry is valid (not at the end of the file).
819 * This method will return true if an emptied (nulled) entry has been found.
821 * @return $isValid Whether the next entry is valid
823 public function valid () {
824 // First calculate minimum block length
825 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
826 $length = $this->getBlockInstance()->calculateMinimumBlockLength();
828 // Short be more than zero!
831 // Get current seek position
832 $seekPosition = $this->key();
834 // Then try to read it
835 $data = $this->read($length);
837 // If some bytes could be read, all is fine
838 $isValid = ((is_string($data)) && (strlen($data) > 0));
841 $headerSize = $this->getHeaderSize();
843 // Is the seek position at or beyond the header?
844 if ($seekPosition >= $headerSize) {
845 // Seek back to old position
846 $this->seek($seekPosition);
848 // Seek directly behind the header
849 $this->seek($headerSize);
857 * Gets current seek position ("key").
859 * @return $key Current key in iteration
861 public function key () {
862 // Call pointer instance
863 return $this->getPointerInstance()->determineSeekPosition();
867 * Reads the file header
871 public function readFileHeader () {
872 // Call block instance
873 $this->getBlockInstance()->readFileHeader();
877 * Flushes the file header
881 public function flushFileHeader () {
882 // Call block instance
883 $this->getBlockInstance()->flushFileHeader();
887 * Searches for next suitable gap the given length of data can fit in
888 * including padding bytes.
890 * @param $length Length of raw data
891 * @return $seekPosition Found next gap's seek position
892 * @throws InvalidArgumentException If the parameter is not valid
894 public function searchNextGap (int $length) {
895 // If the file is only gaps, no need to seek
896 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: length=%d - CALLED!', $length));
899 throw new InvalidArgumentException(sprintf('length=%d is not valid', $length));
900 } elseif ($this->isFileOnlyGaps()) {
901 // The first empty block is the first one right after the header
902 return ($this->getHeaderSize() + 1);
906 $this->partialStub('length=' . $length);