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;
11 use Org\Mxchange\CoreFramework\Stack\File\StackableFile;
12 use Org\Mxchange\CoreFramework\Index\Stack\IndexableStack;
13 use Org\Mxchange\CoreFramework\Traits\Index\Stack\IndexableStackTrait;
14 use Org\Mxchange\CoreFramework\Traits\Stack\StackableTrait;
17 use \BadMethodCallException;
18 use \InvalidArgumentException;
21 use \UnexpectedValueException;
24 * A general binary file class
26 * @author Roland Haeder <webmaster@ship-simu.org>
28 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
29 * @license GNU GPL 3.0 or any newer version
30 * @link http://www.ship-simu.org
32 * This program is free software: you can redistribute it and/or modify
33 * it under the terms of the GNU General Public License as published by
34 * the Free Software Foundation, either version 3 of the License, or
35 * (at your option) any later version.
37 * This program is distributed in the hope that it will be useful,
38 * but WITHOUT ANY WARRANTY; without even the implied warranty of
39 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
40 * GNU General Public License for more details.
42 * You should have received a copy of the GNU General Public License
43 * along with this program. If not, see <http://www.gnu.org/licenses/>.
45 abstract class BaseBinaryFile extends BaseAbstractFile implements BinaryFile {
48 use IndexableStackTrait;
51 * Separator for header data
53 const SEPARATOR_HEADER_DATA = 0x01;
56 * Separator header->entries
58 const SEPARATOR_HEADER_ENTRIES = 0x02;
61 * Separator group->hash
63 const SEPARATOR_GROUP_HASH = 0x03;
66 * Separator hash->value
68 const SEPARATOR_HASH_VALUE = 0x04;
71 * Separator entry->entry
73 const SEPARATOR_ENTRIES = 0x05;
76 * Separator type->position
78 const SEPARATOR_TYPE_POSITION = 0x06;
83 const LENGTH_COUNT = 20;
88 const LENGTH_POSITION = 20;
93 const LENGTH_GROUP = 10;
96 * Maximum length of entry type
98 const LENGTH_TYPE = 20;
100 //***** Array elements for 'gaps' array *****
105 const GAPS_INDEX_START = 'start';
110 const GAPS_INDEX_END = 'end';
113 * Current seek position
115 private $seekPosition = 0;
120 private $headerSize = 0;
125 private $header = [];
128 * Seek positions for gaps ("fragmentation")
133 * Seek positions for damaged entries (e.g. mismatching hash sum, ...)
135 private $damagedEntries = [];
140 private $backBuffer = '';
143 * Currently loaded block (will be returned by current())
145 private $currentBlock = '';
148 * Protected constructor
150 * @param $className Name of the class
153 protected function __construct (string $className) {
154 // Call parent constructor
155 parent::__construct($className);
157 // Init counters and gaps array
158 $this->initCountersGapsArray();
162 * Setter for backBuffer field
164 * @param $backBuffer Characters to "store" in back-buffer
167 private function setBackBuffer (string $backBuffer) {
168 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Setting backBuffer(%d)=%s - CALLED!', strlen($backBuffer), $backBuffer));
169 $this->backBuffer = $backBuffer;
173 * Getter for backBuffer field
175 * @return $backBuffer Characters "stored" in back-buffer
177 private function getBackBuffer () {
178 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Getting this->backBuffer(%d)=%s - CALLED!', strlen($this->backBuffer), $this->backBuffer));
179 return $this->backBuffer;
183 * Setter for current field
185 * @param $current Characters to set a currently loaded block
188 private function setCurrentBlock (string $currentBlock) {
189 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Setting currentBlock(%d)=%s - CALLED!', strlen($currentBlock), $currentBlock));
190 $this->currentBlock = $currentBlock;
194 * Gets currently read data
196 * @return $current Currently read data
198 public function getCurrentBlock () {
199 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Getting this->currentBlock(%d)=%s - CALLED!', strlen($this->currentBlock), $this->currentBlock));
200 return $this->currentBlock;
204 * Getter for header size
206 * @return $totalEntries Size of file header
208 public final function getHeaderSize () {
209 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Getting this->headerSize=%d - CALLED!', $this->headerSize));
210 return $this->headerSize;
214 * Setter for header size
216 * @param $headerSize Size of file header
219 public final function setHeaderSize (int $headerSize) {
220 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Setting headerSize=%d - CALLED!', $headerSize));
221 $this->headerSize = $headerSize;
225 * Getter for header array
227 * @return $totalEntries Size of file header
229 public final function getHeader () {
231 return $this->header;
237 * @param $header Array for a file header
240 public final function setHeader (array $header) {
242 $this->header = $header;
246 * Getter for seek position
248 * @return $seekPosition Current seek position (stored here in object)
250 public final function getSeekPosition () {
251 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Getting this->seekPosition=%d - CALLED!', $this->seekPosition));
252 return $this->seekPosition;
256 * Setter for seek position
258 * @param $seekPosition Current seek position (stored here in object)
261 protected final function setSeekPosition (int $seekPosition) {
262 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Setting seekPosition=%d - CALLED!', $seekPosition));
263 $this->seekPosition = $seekPosition;
267 * Marks whole file as gaps-only (freshly created file
269 * @param $type Type of file
270 * @param $minimumBlockLength Minimum block length
273 private function markFileGapsOnly (string $type, int $minimumBlockLength) {
274 // Very simple to do ...
275 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: type=%s,minimumBlockLength=%d - CALLED!', $type, $minimumBlockLength));
276 for ($idx = 0; $idx < FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($type . '_pre_allocate_count'); $idx++) {
277 // Mark start and end position as gap
278 $this->addGap($idx * $minimumBlockLength, $idx * $minimumBlockLength + $minimumBlockLength);
282 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
286 * Checks whether the abstracted file only contains gaps by counting all
287 * gaps' bytes together and compare it to total length.
289 * @return $isGapsOnly Whether the abstracted file only contains gaps
291 private function isFileGapsOnly () {
293 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
295 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: this->gaps()=%d', count($this->gaps)));
296 foreach ($this->gaps as $gap) {
297 // Calculate size of found gap: end-start including both
298 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: gap[%s]=%d,ga[%s]=%d', self::GAPS_INDEX_START, $gap[self::GAPS_INDEX_START], self::GAPS_INDEX_END, $gap[self::GAPS_INDEX_END]));
299 $gapsSize += ($gap[self::GAPS_INDEX_END] - $gap[self::GAPS_INDEX_START]);
302 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: gapsSize=%d', $gapsSize));
305 // Total gap size + header size must be same as file size
306 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: gapsSize=%d,this->fileSize=%d', $gapsSize, $this->getFileSize()));
307 $isGapsOnly = ($gapsSize + 1 == $this->getFileSize());
310 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: isGapsOnly=%d - EXIT!', intval($isGapsOnly)));
315 * Adds a gap for given start and end position
317 * @param $startPosition Start seek position
318 * @param $endPosition End seek position
321 private function addGap(int $startPosition, int $endPosition) {
322 // Push to gaps array
323 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: startPosition=%d,endPosition=%d - CALLED!', $startPosition, $endPosition));
324 array_push($this->gaps, [
325 self::GAPS_INDEX_START => $startPosition,
326 self::GAPS_INDEX_END => $endPosition,
330 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
334 * Initializes the back-buffer by setting it to an empty string.
338 private function initBackBuffer () {
339 // Simply call the setter
340 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
341 $this->setBackBuffer('');
344 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
348 * Seeks to beginning of file, updates seek position in this object and
349 * flushes the header.
351 * @param $flushHeader Wether the file's header should be flushed (default: false)
354 protected function rewindUpdateSeekPosition (bool $flushHeader = false) {
355 // Seek to beginning of file
356 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: flushHeader=%d - CALLED!', intval($flushHeader)));
359 // And update seek position ...
360 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->updateSeekPosition() ...');
361 $this->updateSeekPosition();
365 // ... to write it back into the file
366 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->flushFileHeader() ...');
367 $this->flushFileHeader();
371 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
375 * Seeks to old position
379 protected function seekToOldPosition () {
380 // Seek to currently ("old") saved position
381 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
382 $this->seek($this->determineSeekPosition());
385 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
389 * Initializes this file class
391 * @param $fileInfoInstance An instance of a SplFileInfo class
394 protected function initFile (SplFileInfo $fileInfoInstance) {
395 // Get a file i/o pointer instance
396 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: fileInfoInstance[%s]=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance));
397 $pointerInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_output_class', array($fileInfoInstance));
399 // ... and set it here
400 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Setting pointerInstance=%s ...', $pointerInstance->__toString()));
401 $this->setPointerInstance($pointerInstance);
404 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
408 * Marks the currently loaded block as empty (with length of the block)
410 * @param $length Length of the block
412 * @throws InvalidArgumentException If a parameter is invalid
414 protected function markCurrentBlockAsEmpty (int $length) {
415 // Validate parameter
416 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: length=%d - CALLED!', $length));
418 // Length cannot below one
419 throw new InvalidArgumentException(sprintf('length=%d is not valid', $length));
422 // Get current seek position
423 $currentPosition = $this->determineSeekPosition();
425 // Now add it as gap entry
426 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: currentPosition=%d', $currentPosition));
427 $this->addGap(($currentPosition - $length), $currentPosition);
430 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
434 * Initializes counter for valid entries, arrays for damaged entries and
435 * an array for gap seek positions. If you call this method on your own,
436 * please re-analyze the file structure. So you are better to call
437 * analyzeFileStructure() instead of this method.
441 public function initCountersGapsArray () {
442 // Init counter and seek position to header size
443 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
444 $this->setCounter(0);
445 $this->setSeekPosition($this->getHeaderSize());
449 $this->damagedEntries = [];
452 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
456 * Updates seekPosition attribute from file to avoid to much access on file.
460 public function updateSeekPosition () {
461 // Get key (= seek position)
462 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
463 $seekPosition = $this->determineSeekPosition();
466 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%d', $seekPosition));
467 $this->setSeekPosition($seekPosition);
470 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
474 * Checks whether the block separator has been found
476 * @param $str String to look in
477 * @return $isFound Whether the block separator has been found
478 * @throws InvalidArgumentException If a parameter is not valid
480 public static function isBlockSeparatorFound (string $str) {
481 // Validate parameter
482 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: str=%s - CALLED!', $str));
485 throw new InvalidArgumentException('Parameter "str" is empty');
489 $isFound = (strpos($str, chr(self::SEPARATOR_ENTRIES)) !== false);
492 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: isFound=%d - EXIT!', intval($isFound)));
497 * Writes data at given position
499 * @param $seekPosition Seek position
500 * @param $data Data to be written
501 * @param $flushHeader Whether to flush the header (default: flush)
503 * @throws InvalidArgumentException If a parameter is invalid
505 public function writeData (int $seekPosition, string $data, bool $flushHeader = true) {
506 // Validate parameter
507 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%s,data()=%d,flushHeader=%d - CALLED!', $seekPosition, strlen($data), intval($flushHeader)));
508 if ($seekPosition < 0) {
509 // Invalid seek position
510 throw new InvalidArgumentException(sprintf('seekPosition=%d is not valid', $seekPosition));
511 } elseif (empty($data)) {
512 // Empty data is invalid, too
513 throw new InvalidArgumentException('Parameter "data" is empty');
516 // Write data at given position
517 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling this->writeAtPosition(%d,%s) ...', $seekPosition, $data));
518 $this->writeAtPosition($seekPosition, $data);
521 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->incrementCounter() ...');
522 $this->incrementCounter();
524 // Update seek position
525 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->updateSeekPosition() ...');
526 $this->updateSeekPosition();
529 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: flushHeader=%d', intval($flushHeader)));
530 if ($flushHeader === true) {
532 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->flushFileHeader() ...');
533 $this->flushFileHeader();
535 // Seek to old position
536 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->seekToOldPosition() ...');
537 $this->seekToOldPosition();
541 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
545 * Writes at given position by seeking to it.
547 * @param $seekPosition Seek position in file
548 * @param $dataStream Data to be written
549 * @return mixed Number of writes bytes or false on error
550 * @throws InvalidArgumentException If a parameter is not valid
552 public function writeAtPosition (int $seekPosition, string $dataStream) {
553 // Validate parameter
554 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%d,dataStream(%d)=%s - CALLED!', $seekPosition, strlen($dataStream), $dataStream));
555 if ($seekPosition < 0) {
556 // Invalid seek position
557 throw new InvalidArgumentException(sprintf('seekPosition=%d is not valid.', $seekPosition));
558 } elseif (empty($dataStream)) {
560 throw new InvalidArgumentException('Parameter "dataStream" is empty');
563 // Call pointer's method
564 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling this->pointerInstance->writeAtPosition(%d, %s) ...', $seekPosition, $dataStream));
565 $status = $this->getPointerInstance()->writeAtPosition($seekPosition, $dataStream);
568 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: status[%s]=%d - EXIT!', gettype($status), $status));
573 * Checks whether the file header is initialized
575 * @return $isInitialized Whether the file header is initialized
577 public function isFileHeaderInitialized () {
578 // Default is not initialized
579 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
580 $isInitialized = false;
582 // Is the file initialized?
583 if ($this->isFileInitialized()) {
584 // Some bytes has been written, so rewind to start of it.
588 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->readFileHeader() ...');
589 $this->readFileHeader();
592 $headerCount = count($this->getHeader());
594 // The above method does already check the header
595 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: headerCount=%d', $headerCount));
596 $isInitialized = ($headerCount > 0);
600 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: isInitialized=%d - EXIT!', intval($isInitialized)));
601 return $isInitialized;
605 * Checks whether the assigned file has been initialized
607 * @return $isInitialized Whether the file's size is zero
608 * @throws UnexpectedValueException If an unexpected value was returned
610 public function isFileInitialized () {
611 // Get it from iterator which holds the pointer instance. If false is returned
612 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
613 $fileSize = $this->size();
616 * The returned file size should not be false or NULL as this means
617 * that the pointer class does not work correctly.
619 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: fileSize[%s]=%d', gettype($fileSize), $fileSize));
620 if (!is_int($fileSize)) {
622 throw new UnexpectedValueException(sprintf('fileSize[]=%s is unexpected', gettype($fileSize)));
625 // Is more than 0 returned?
626 $isInitialized = ($fileSize > 0);
629 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: isInitialized=%d - EXIT!', intval($isInitialized)));
630 return $isInitialized;
634 * Creates the assigned file
637 * @throws BadMethodCallException If this file's header is already initialized
639 public function createFileHeader () {
640 // The file's header should not be initialized here
641 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
642 if ($this->isFileHeaderInitialized()) {
644 //* DEBUG-DIE: */ die(sprintf('[%s:%d]: this=%s', __METHOD__, __LINE__, print_r($this, TRUE)));
645 throw new BadMethodCallException('File header is already initialized but method called');
648 // Simple flush file header which will create it.
649 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->flushFileHeader() ...');
650 $this->flushFileHeader();
652 // Rewind seek position (to beginning of file) and update/flush file header
653 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->rewindUpdateSeekPosition() ...');
654 $this->rewindUpdateSeekPosition();
657 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
661 * Pre-allocates file (if enabled) with some space for later faster write access.
663 * @param $type Type of the file
665 * @throws InvalidArgumentException If a parameter is empty
667 public function preAllocateFile (string $type) {
669 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: type=%s - CALLED!', $type));
672 throw new InvalidArgumentException('Parameter "type" is empty');
673 } elseif (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($type . '_pre_allocate_enabled') != 'Y') {
674 // Don't continue here.
675 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Not pre-allocating file.'));
680 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Pre-allocating file ...');
682 // Calculate minimum length for one entry and get file size
683 $minimumBlockLength = $this->getIndexableStackInstance()->calculateMinimumBlockLength();
684 $fileSize = $this->getFileSize();
686 // Calulcate seek position
687 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: minimumBlockLength=%d,fileSize=%d', $minimumBlockLength, $fileSize));
688 $seekPosition = $minimumBlockLength * FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($type . '_pre_allocate_count') + $fileSize ;
690 // Now simply write a NUL there. This will pre-allocate the file.
691 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling this->writeAtPosition(%d,NUL) ...', $seekPosition));
692 $this->writeAtPosition($seekPosition, chr(0));
694 // Is the seek position zero?
695 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: fileSize=%d', $fileSize));
696 if ($fileSize == 0) {
697 // Mark file as gaps-only
698 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling this->markGapsOnly(%s,%d) ...', $type, $minimumBlockLength));
699 $this->markFileGapsOnly($type, $minimumBlockLength);
701 // Analyze file structure
702 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->analyzeFileStructure() ...');
703 $this->analyzeFileStructure();
706 // Rewind seek position
707 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->rewind() ...');
711 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
715 * Determines seek position
717 * @return $seekPosition Current seek position
719 public function determineSeekPosition () {
720 // Call pointer instance
721 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
722 $seekPosition = $this->getPointerInstance()->determineSeekPosition();
725 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%d - EXIT!', $seekPosition));
726 return $seekPosition;
730 * Seek to given offset (default) or other possibilities as fseek() gives.
732 * @param $offset Offset to seek to (or used as "base" for other seeks)
733 * @param $whence Added to offset (default: only use offset to seek to)
734 * @return $status Status of file seek: 0 = success, -1 = failed
735 * @throws InvalidArgumentException If a parameter is not valid
737 public function seek (int $offset, int $whence = SEEK_SET) {
738 // Validate parameter
739 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: offset=%d,whence=%d - CALLED!', $offset, $whence));
741 // No offset is smaller than zero
742 throw new InvalidArgumentException(sprintf('offset=%d is not valid', $offset));
745 // Call pointer instance
746 $status = $this->getPointerInstance()->seek($offset, $whence);
749 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: status[%s]=%d - EXIT!', gettype($status), $status));
754 * Reads given amount of bytes from file.
756 * @param $bytes Amount of bytes to read
757 * @return $data Data read from file
758 * @throws InvalidArgumentException If a parameter is not valid
760 public function read (int $bytes = 0) {
761 // Validate parameter
762 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: bytes=%d - CALLED!', $bytes));
765 throw new InvalidArgumentException(sprintf('bytes=%d is not valid', $bytes));
768 // Call pointer instance
769 $data = $this->getPointerInstance()->read($bytes);
772 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: data[%s]=%s - EXIT!', gettype($data), $data));
777 * Rewinds to the beginning of the file
781 public function rewind () {
782 // Call pointer instance
783 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
784 $this->getPointerInstance()->rewind();
787 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
791 * Analyzes entries in index file. This will count all found (and valid)
792 * entries, mark invalid as damaged and count gaps ("fragmentation"). If
793 * only gaps are found, the file is considered as "virgin" (no entries).
796 * @throws BadMethodCallException If this method is called but file is not initialized
798 public function analyzeFileStructure () {
799 // Make sure the file is initialized
800 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
801 if (!$this->isFileInitialized()) {
803 throw new BadMethodCallException('Method called but file is not initialized.');
806 // Init counters and gaps array
807 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->initCounterGapsArrays() ...');
808 $this->initCountersGapsArray();
810 // Output message (as this may take some time)
811 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Analyzing file structure ... (this may take some time)'));
813 // First rewind to the begining
814 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->rewind() ...');
817 // Then try to load all entries
818 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Looping through file');
819 while ($this->isValid()) {
821 $current = $this->getCurrentBlock();
824 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->readNextBlock() ...');
825 $this->readNextBlock();
828 * If the block is empty, maybe the whole file is? This could mean
829 * that the file has been pre-allocated.
831 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: current(%d)[]=%s', strlen($current), gettype($current)));
832 if (empty($current)) {
833 // Then skip this part
834 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: current[]=%s is empty - CONTINUE!', gettype($current)));
838 // Handle current record
839 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: current(%d)[]=%s', strlen($current), gettype($current)));
842 // If the last read block is empty, check gaps
843 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: current()=%d', strlen($current)));
844 if (empty($current)) {
846 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Found a total of %d gaps.', count($this->gaps)));
848 // Check gaps, if the whole file is empty.
849 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->isFileGapsOnly() ...');
850 if ($this->isFileGapsOnly()) {
851 // Only gaps, so don't continue here.
852 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: File is gaps-only - EXIT!');
857 * The above call has calculated a total size of all gaps. If the
858 * percentage of gaps passes a "soft" limit and last
859 * defragmentation is to far in the past, or if a "hard" limit has
860 * reached, run defragmentation.
862 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->isDefragmentationNeeded() ...');
863 if ($this->isDefragmentationNeeded()) {
864 // Run "defragmentation"
865 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->doRunDefragmentation() ...');
866 $this->doRunDefragmentation();
871 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
875 * Reads next "block" of bytes into $currentBlock field
878 * @throws BadMethodCallException If this method was called without prior valid() call
880 public function readNextBlock () {
881 // Is there nothing to read?
882 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
883 if (!$this->isValid()) {
885 throw new BadMethodCallException('next() invoked but no valid current block (EOF?)');
888 // First calculate minimum block length
889 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: this->seekPosition=%d', $this->determineSeekPosition()));
890 $length = $this->getIndexableStackInstance()->calculateMinimumBlockLength();
891 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: length=%d', $length));
893 // Read possibly back-buffered bytes from previous call of next().
894 $data = $this->getBackBuffer();
897 * Read until a entry/block separator has been found. The next read
898 * "block" may not fit, so this loop will continue until the EOB or EOF
899 * has been reached whatever comes first.
901 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: data()=%d', strlen($data)));
902 while ((!$this->isEndOfFileReached()) && (empty($data) || !self::isBlockSeparatorFound($data))) {
903 // Then read the next possible block
904 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling this->read(%d) ...', $length));
905 $block = $this->read($length);
908 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: block()=%d,length=%d', strlen($block), $length));
909 if (strlen(trim($block, chr(0))) == 0) {
910 // Mark this block as empty
911 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling this->markCurrentBlockAsEmpty(%d) ...', strlen($block)));
912 $this->markCurrentBlockAsEmpty(strlen($block));
915 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Empty block found ... - BREAK!');
919 // At this block then
923 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: data(%d)=%s', strlen($data), $data));
927 * Init back-buffer which is the data that has been found beyond the
930 $this->initBackBuffer();
933 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: data(%d)=%s', strlen($data), $data));
935 // Yes, maybe whole file was ...
936 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Maybe empty file found - EXIT!');
941 $dataArray = explode(chr(self::SEPARATOR_ENTRIES), $data);
943 // Left part is the actual block, right one the back-buffer data, if found
944 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: dataArray()=%d', count($dataArray)));
945 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: dataArray=%s', print_r($dataArray, true)));
946 $this->setCurrentBlock($dataArray[0]);
948 // Is back buffere data found?
949 if (isset($dataArray[1])) {
951 $this->setBackBuffer($dataArray[1]);
955 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
959 * Checks wether the current entry is valid (not at the end of the file).
960 * This method will return true if an emptied (nulled) entry has been found.
962 * @return $isValid Whether the next entry is valid
963 * @throws UnexpectedValueException If some value is not expected
965 public function isValid () {
966 // First calculate minimum block length
967 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
968 $length = $this->getIndexableStackInstance()->calculateMinimumBlockLength();
970 // Short be more than zero!
971 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: length=%d', $length));
974 throw new UnexpectedValueException(sprintf('length=%d is not expected', $length));
977 // Get current seek position
978 $seekPosition = $this->determineSeekPosition();
980 // Then try to read it
981 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%d', $seekPosition));
982 $data = $this->read($length);
984 // If some bytes could be read, all is fine
985 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: data[%s]()=%d', gettype($data), strlen($data)));
986 $isValid = ((is_string($data)) && (strlen($data) > 0));
989 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: isValid=%d', intval($isValid)));
990 $headerSize = $this->getHeaderSize();
992 // Is the seek position at or beyond the header?
993 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%d,headerSize=%d', $seekPosition, $headerSize));
994 if ($seekPosition >= $headerSize) {
995 // Seek back to old position
996 $isValid = ($isValid && $this->seek($seekPosition) === 0);
998 // Seek directly behind the header
999 $isValid = ($isValid && $this->seek($headerSize) === 0);
1003 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: isValid=%d - EXIT!', intval($isValid)));
1008 * Reads the file header
1011 * @throws LogicException If both instances are not set
1013 public function readFileHeader () {
1014 // Is index set or stack?
1015 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
1016 if ($this->getIndexableStackInstance() instanceof IndexableStack) {
1017 // Call index instance
1018 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->indexableStackInstance->readFileHeader() ...');
1019 $this->getIndexableStackInstance()->readFileHeader();
1020 } elseif ($this->getStackInstance() instanceof StackableFile) {
1021 // Call stacke instance
1022 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->stackInstance->readFileHeader() ...');
1023 $this->getStackInstance()->readFileHeader();
1026 throw new LogicException('Wether indexableStackInstance nor stackableFileInstance are set');
1030 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
1034 * Flushes the file header
1038 public function flushFileHeader () {
1039 // Call block instance
1040 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
1041 $this->getIndexableStackInstance()->flushFileHeader();
1044 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
1048 * Searches for next suitable gap the given length of data can fit in
1049 * including padding bytes.
1051 * @param $length Length of raw data
1052 * @return $seekPosition Found next gap's seek position
1053 * @throws InvalidArgumentException If the parameter is not valid
1055 public function searchNextGap (int $length) {
1056 // If the file is only gaps, no need to seek
1057 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: length=%d - CALLED!', $length));
1060 throw new InvalidArgumentException(sprintf('length=%d is not valid', $length));
1061 } elseif ($this->isFileGapsOnly()) {
1063 * The first empty block is the 2nd one right after the header, so
1064 * one byte gap to the header.
1066 $seekPosition = ($this->getHeaderSize() + 2);
1069 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%d - EXIT!', $seekPosition));
1070 return $seekPosition;
1074 $this->partialStub('length=' . $length);