3 namespace Org\Mxchange\CoreFramework\Filesystem\File;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
8 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
9 use Org\Mxchange\CoreFramework\Filesystem\File\BaseAbstractFile;
10 use Org\Mxchange\CoreFramework\Filesystem\FilePointer;
11 use Org\Mxchange\CoreFramework\Traits\Index\IndexableTrait;
12 use Org\Mxchange\CoreFramework\Traits\Stack\StackableTrait;
15 use \BadMethodCallException;
16 use \InvalidArgumentException;
18 use \OutOfBoundsException;
20 use \UnexpectedValueException;
23 * A general binary file class
25 * @author Roland Haeder <webmaster@ship-simu.org>
27 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2022 Core Developer Team
28 * @license GNU GPL 3.0 or any newer version
29 * @link http://www.ship-simu.org
31 * This program is free software: you can redistribute it and/or modify
32 * it under the terms of the GNU General Public License as published by
33 * the Free Software Foundation, either version 3 of the License, or
34 * (at your option) any later version.
36 * This program is distributed in the hope that it will be useful,
37 * but WITHOUT ANY WARRANTY; without even the implied warranty of
38 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39 * GNU General Public License for more details.
41 * You should have received a copy of the GNU General Public License
42 * along with this program. If not, see <http://www.gnu.org/licenses/>.
44 abstract class BaseBinaryFile extends BaseAbstractFile implements BinaryFile {
52 private static $configCache = [];
55 * Current seek position
57 private $seekPosition = 0;
62 private $headerSize = 0;
70 * Seek positions for gaps ("fragmentation")
75 * Seek positions for damaged entries (e.g. mismatching hash sum, ...)
77 private $damagedEntries = [];
82 private $backBuffer = '';
85 * Currently loaded block (will be returned by current())
87 private $currentBlock = '';
90 * Protected constructor
92 * @param $className Name of the class
95 protected function __construct (string $className) {
96 // Call parent constructor
97 parent::__construct($className);
101 * Setter for backBuffer field
103 * @param $backBuffer Characters to "store" in back-buffer
106 private function setBackBuffer (string $backBuffer) {
107 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Setting backBuffer(%d)=%s - CALLED!', strlen($backBuffer), $backBuffer));
108 $this->backBuffer = $backBuffer;
112 * Getter for backBuffer field
114 * @return $backBuffer Characters "stored" in back-buffer
116 private function getBackBuffer () {
117 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Getting this->backBuffer(%d)=%s - CALLED!', strlen($this->backBuffer), $this->backBuffer));
118 return $this->backBuffer;
122 * Setter for current field
124 * @param $current Characters to set a currently loaded block
127 private function setCurrentBlock (string $currentBlock) {
128 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Setting currentBlock(%d)=%s - CALLED!', strlen($currentBlock), $currentBlock));
129 $this->currentBlock = $currentBlock;
133 * Gets currently read data
135 * @return $current Currently read data
137 public function getCurrentBlock () {
138 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Getting this->currentBlock(%d)=%s - CALLED!', strlen($this->currentBlock), $this->currentBlock));
139 return $this->currentBlock;
143 * Getter for header size
145 * @return $totalEntries Size of file header
147 public final function getHeaderSize () {
148 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Getting this->headerSize=%d - CALLED!', $this->headerSize));
149 return $this->headerSize;
153 * Setter for header size
155 * @param $headerSize Size of file header
158 public final function setHeaderSize (int $headerSize) {
159 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Setting headerSize=%d - CALLED!', $headerSize));
160 $this->headerSize = $headerSize;
164 * Getter for header array
166 * @return $totalEntries Size of file header
168 public final function getHeader () {
170 return $this->header;
176 * @param $header Array for a file header
179 public final function setHeader (array $header) {
181 $this->header = $header;
185 * Getter for seek position
187 * @return $seekPosition Current seek position (stored here in object)
189 public final function getSeekPosition () {
190 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Getting this->seekPosition=%d - CALLED!', $this->seekPosition));
191 return $this->seekPosition;
195 * Setter for seek position
197 * @param $seekPosition Current seek position (stored here in object)
200 protected final function setSeekPosition (int $seekPosition) {
201 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Setting seekPosition=%d - CALLED!', $seekPosition));
202 $this->seekPosition = $seekPosition;
206 * Checks whether the abstracted file only contains gaps by counting all
207 * gaps' bytes together and compare it to total length.
209 * @return $isGapsOnly Whether the abstracted file only contains gaps
210 * @throws OutOfBoundsException If calculated file size is larger than actual
212 public function isFileGapsOnly () {
214 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
216 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: this->gaps()=%d', count($this->gaps)));
217 foreach ($this->gaps as $gap) {
218 // Calculate size of found gap: end-start including both
219 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: gap[%s]=%d,ga[%s]=%d', BinaryFile::GAPS_INDEX_START, $gap[BinaryFile::GAPS_INDEX_START], BinaryFile::GAPS_INDEX_END, $gap[BinaryFile::GAPS_INDEX_END]));
220 $gapsSize += ($gap[BinaryFile::GAPS_INDEX_END] - $gap[BinaryFile::GAPS_INDEX_START]);
223 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: gapsSize=%d', $gapsSize));
226 // Total gap size + header size + 1 must be same as file size
227 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: gapsSize=%d,this->headerSize=%d,this->fileSize=%d', $gapsSize, $this->getHeaderSize(), $this->getFileSize()));
228 $determinedFileSize = ($gapsSize + $this->getHeaderSize() + 1);
230 // Should not be more!
231 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: determinedFileSize=%d,this->fileSize=%d', $determinedFileSize, $this->getFileSize()));
232 if ($determinedFileSize > $this->getFileSize()) {
234 throw new OutOfBoundsException(sprintf('determinedFileSize=%d is larger than this->fileSize=%d', $determinedFileSize, $this->getFileSize()));
238 $isGapsOnly = ($determinedFileSize == $this->getFileSize());
241 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: isGapsOnly=%d - EXIT!', intval($isGapsOnly)));
246 * Marks whole file as gaps-only (freshly created file
248 * @param $type Type of file
249 * @param $minimumBlockLength Minimum block length
252 private function markFileGapsOnly (string $type, int $minimumBlockLength) {
253 // Is config cache there?
254 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: type=%s,minimumBlockLength=%d - CALLED!', $type, $minimumBlockLength));
255 if (!isset(self::$configCache[$type . '_pre_allocate_count'])) {
257 self::$configCache[$type . '_pre_allocate_count'] = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($type . '_pre_allocate_count');
260 // Very simple to do ...
261 for ($idx = 0; $idx < self::$configCache[$type . '_pre_allocate_count']; $idx++) {
262 // Calculate start/end positions
263 $startPosition = $idx * $minimumBlockLength;
264 $endPosition = $idx * $minimumBlockLength + $minimumBlockLength;
266 // Mark start and end position as gap
267 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling this->addGap(%d, %d) ...', $startPosition, $endPosition));
268 $this->addGap($startPosition, $endPosition);
272 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
276 * Adds a gap for given start and end position
278 * @param $startPosition Start seek position
279 * @param $endPosition End seek position
282 private function addGap(int $startPosition, int $endPosition) {
283 // Push to gaps array
284 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: startPosition=%d,endPosition=%d - CALLED!', $startPosition, $endPosition));
285 array_push($this->gaps, [
286 BinaryFile::GAPS_INDEX_START => $startPosition,
287 BinaryFile::GAPS_INDEX_END => $endPosition,
291 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
295 * Initializes the back-buffer by setting it to an empty string.
299 private function initBackBuffer () {
300 // Simply call the setter
301 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
302 $this->setBackBuffer('');
305 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
309 * Seeks to beginning of file, updates seek position in this object and
310 * flushes the header.
312 * @param $flushHeader Wether the file's header should be flushed (default: false)
315 protected function rewindUpdateSeekPosition (bool $flushHeader = false) {
316 // Seek to beginning of file
317 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: flushHeader=%d - CALLED!', intval($flushHeader)));
320 // And update seek position ...
321 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->updateSeekPosition() ...');
322 $this->updateSeekPosition();
326 // ... to write it back into the file
327 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->flushFileHeader() ...');
328 $this->flushFileHeader();
332 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
336 * Seeks to old position
340 protected function seekToOldPosition () {
341 // Seek to currently ("old") saved position
342 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
343 $this->seek($this->determineSeekPosition());
346 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
350 * Initializes this file class
352 * @param $fileInfoInstance An instance of a SplFileInfo class
355 protected function initFile (SplFileInfo $fileInfoInstance) {
356 // Get a file i/o pointer instance
357 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: fileInfoInstance[%s]=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance));
358 $pointerInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_output_class', array($fileInfoInstance));
360 // ... and set it here
361 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Setting pointerInstance=%s ...', $pointerInstance->__toString()));
362 $this->setPointerInstance($pointerInstance);
365 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
369 * Marks the currently loaded block as empty (with length of the block)
371 * @param $length Length of the block
373 * @throws InvalidArgumentException If a parameter is invalid
375 protected function markCurrentBlockAsEmpty (int $length) {
376 // Validate parameter
377 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: length=%d - CALLED!', $length));
379 // Length cannot below one
380 throw new InvalidArgumentException(sprintf('length=%d is not valid', $length));
383 // Get current seek position
384 $currentPosition = $this->determineSeekPosition();
386 // Now add it as gap entry
387 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling this->addGap(%d, %d) ..', ($currentPosition - $length), $currentPosition));
388 $this->addGap(($currentPosition - $length), $currentPosition);
391 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
395 * Initializes counter for valid entries, arrays for damaged entries and
396 * an array for gap seek positions. If you call this method on your own,
397 * please re-analyze the file structure. So you are better to call
398 * analyzeFileStructure() instead of this method.
402 public function initCountersGapsArray () {
403 // Init counter and seek position to header size
404 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->determineSeekPosition() - CALLED!');
405 $seekPosition = $this->getSeekPosition();
408 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%d', $seekPosition));
409 $this->setCounter(0);
412 $headerSize = $this->getHeaderSize();
415 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Setting this->seekPosition=%d ...', $headerSize));
416 $this->setSeekPosition($headerSize);
420 $this->damagedEntries = [];
422 // Seek back to old position
423 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling this->seek(%d) ...', $seekPosition));
424 $this->seek($seekPosition);
427 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
431 * Updates seekPosition attribute from file to avoid to much access on file.
435 public function updateSeekPosition () {
436 // Get key (= seek position)
437 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
438 $seekPosition = $this->determineSeekPosition();
441 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%d', $seekPosition));
442 $this->setSeekPosition($seekPosition);
445 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
449 * Checks whether the block separator has been found
451 * @param $str String to look in
452 * @return $isFound Whether the block separator has been found
453 * @throws InvalidArgumentException If a parameter is not valid
455 public static function isBlockSeparatorFound (string $str) {
456 // Validate parameter
457 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: str=%s - CALLED!', $str));
460 throw new InvalidArgumentException('Parameter "str" is empty');
464 $isFound = (strpos($str, chr(BinaryFile::SEPARATOR_ENTRIES)) !== false);
467 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: isFound=%d - EXIT!', intval($isFound)));
472 * Writes data at given position
474 * @param $seekPosition Seek position
475 * @param $data Data to be written
476 * @param $flushHeader Whether to flush the header (default: flush)
478 * @throws OutOfBoundsException If the position is not seekable
479 * @throws InvalidArgumentException If a parameter is invalid
481 public function writeData (int $seekPosition, string $data, bool $flushHeader = true) {
482 // Validate parameter
483 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%s,data()=%d,flushHeader=%d - CALLED!', $seekPosition, strlen($data), intval($flushHeader)));
484 if ($seekPosition < 0) {
485 // Invalid seek position
486 throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid', $seekPosition));
487 } elseif (empty($data)) {
488 // Empty data is invalid, too
489 throw new InvalidArgumentException('Parameter "data" is empty');
492 // Write data at given position
493 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling this->writeAtPosition(%d,%s) ...', $seekPosition, $data));
494 $this->writeAtPosition($seekPosition, $data);
497 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->incrementCounter() ...');
498 $this->incrementCounter();
500 // Update seek position
501 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->updateSeekPosition() ...');
502 $this->updateSeekPosition();
505 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: flushHeader=%d', intval($flushHeader)));
506 if ($flushHeader === true) {
508 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->flushFileHeader() ...');
509 $this->flushFileHeader();
511 // Seek to old position
512 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->seekToOldPosition() ...');
513 $this->seekToOldPosition();
517 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
521 * Writes at given position by seeking to it.
523 * @param $seekPosition Seek position in file
524 * @param $dataStream Data to be written
525 * @return mixed Number of writes bytes or false on error
526 * @throws OutOfBoundsException If the position is not seekable
527 * @throws InvalidArgumentException If a parameter is not valid
529 public function writeAtPosition (int $seekPosition, string $dataStream) {
530 // Validate parameter
531 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%d,dataStream(%d)=%s - CALLED!', $seekPosition, strlen($dataStream), $dataStream));
532 if ($seekPosition < 0) {
533 // Invalid seek position
534 throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid.', $seekPosition));
535 } elseif (empty($dataStream)) {
537 throw new InvalidArgumentException('Parameter "dataStream" is empty');
540 // Call pointer's method
541 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling this->pointerInstance->writeAtPosition(%d, %s) ...', $seekPosition, $dataStream));
542 $status = $this->getPointerInstance()->writeAtPosition($seekPosition, $dataStream);
545 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: status[%s]=%d - EXIT!', gettype($status), $status));
550 * Checks whether the file header is initialized
552 * @return $isInitialized Whether the file header is initialized
554 public function isFileHeaderInitialized () {
555 // Default is not initialized
556 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
557 $isInitialized = false;
559 // Is the file initialized?
560 if ($this->isFileInitialized()) {
561 // Some bytes has been written, so rewind to start of it.
565 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->readFileHeader() ...');
566 $this->readFileHeader();
569 $headerCount = count($this->getHeader());
571 // The above method does already check the header
572 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: headerCount=%d', $headerCount));
573 $isInitialized = ($headerCount > 0);
577 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: isInitialized=%d - EXIT!', intval($isInitialized)));
578 return $isInitialized;
582 * Checks whether the assigned file has been initialized
584 * @return $isInitialized Whether the file's size is zero
585 * @throws UnexpectedValueException If an unexpected value was returned
587 public function isFileInitialized () {
588 // Get it from iterator which holds the pointer instance. If false is returned
589 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
590 $fileSize = $this->size();
593 * The returned file size should not be false or NULL as this means
594 * that the pointer class does not work correctly.
596 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: fileSize[%s]=%d', gettype($fileSize), $fileSize));
597 if (!is_int($fileSize)) {
599 throw new UnexpectedValueException(sprintf('fileSize[]=%s is unexpected', gettype($fileSize)));
602 // Is more than 0 returned?
603 $isInitialized = ($fileSize > 0);
606 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: isInitialized=%d - EXIT!', intval($isInitialized)));
607 return $isInitialized;
611 * Creates the assigned file
614 * @throws BadMethodCallException If this file's header is already initialized
616 public function createFileHeader () {
617 // The file's header should not be initialized here
618 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
619 if ($this->isFileHeaderInitialized()) {
621 //* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this=%s', __METHOD__, __LINE__, print_r($this, TRUE)));
622 throw new BadMethodCallException('File header is already initialized but method called');
625 // Simple flush file header which will create it.
626 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->flushFileHeader() ...');
627 $this->flushFileHeader();
629 // Rewind seek position (to beginning of file) and update/flush file header
630 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->rewindUpdateSeekPosition() ...');
631 $this->rewindUpdateSeekPosition();
634 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
638 * Determines seek position
640 * @return $seekPosition Current seek position
642 public function determineSeekPosition () {
643 // Call pointer instance
644 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
645 $seekPosition = $this->getPointerInstance()->determineSeekPosition();
648 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%d - EXIT!', $seekPosition));
649 return $seekPosition;
653 * Seek to given offset (default) or other possibilities as fseek() gives.
655 * @param $offset Offset to seek to (or used as "base" for other seeks)
656 * @param $whence Added to offset (default: only use offset to seek to)
657 * @return $status Status of file seek: 0 = success, -1 = failed
658 * @throws OutOfBoundsException If the position is not seekable
660 public function seek (int $offset, int $whence = SEEK_SET) {
661 // Validate parameter
662 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: offset=%d,whence=%d - CALLED!', $offset, $whence));
664 // No offset is smaller than zero
665 throw new OutOfBoundsException(sprintf('offset=%d is not valid', $offset));
668 // Call pointer instance
669 $status = $this->getPointerInstance()->seek($offset, $whence);
672 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: status[%s]=%d - EXIT!', gettype($status), $status));
677 * Reads given amount of bytes from file.
679 * @param $bytes Amount of bytes to read
680 * @return $data Data read from file
681 * @throws OutOfBoundsException If the position is not seekable
683 public function read (int $bytes = 0) {
684 // Validate parameter
685 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: bytes=%d - CALLED!', $bytes));
688 throw new OutOfBoundsException(sprintf('bytes=%d is not valid', $bytes));
691 // Call pointer instance
692 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling this->pointerInstance->read(%d) ...', $bytes));
693 $data = $this->getPointerInstance()->read($bytes);
695 // Update seek position
696 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->updateSeekPosition() ...');
697 $this->updateSeekPosition();
700 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: data[%s]=%s - EXIT!', gettype($data), $data));
705 * Rewinds to the beginning of the file
709 public function rewind () {
710 // Call pointer instance
711 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
712 $this->getPointerInstance()->rewind();
715 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
719 * Analyzes entries in index file. This will count all found (and valid)
720 * entries, mark invalid as damaged and count gaps ("fragmentation"). If
721 * only gaps are found, the file is considered as "virgin" (no entries).
724 * @throws BadMethodCallException If this method is called but file is not initialized
726 public function analyzeFileStructure () {
727 // Make sure the file is initialized
728 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: CALLED!');
729 if (!$this->isFileInitialized()) {
731 throw new BadMethodCallException('Method called but file is not initialized.');
734 // Init counters and gaps array
735 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->initCounterGapsArrays() ...');
736 $this->initCountersGapsArray();
738 // Output message (as this may take some time)
739 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Analyzing file structure ... (this may take some time)'));
741 // First Seek to right after file header
742 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling this->seek(%d) ...', $this->getHeaderSize() + 1));
743 $this->seek($this->getHeaderSize() + 1);
745 // Then try to load all entries
746 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: this->seekPosition=%d, looping through file ...', $this->getSeekPosition()));
747 while ($this->isValid()) {
749 $current = $this->getCurrentBlock();
752 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: current=%s, calling this->readNextBlock() ...', $current));
753 $this->readNextBlock();
756 * If the block is empty, maybe the whole file is? This could mean
757 * that the file has been pre-allocated.
759 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: current(%d)[]=%s', strlen($current), gettype($current)));
760 if (empty(trim($current, chr(0)))) {
761 // Then skip this part
762 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: current[]=%s is empty - CONTINUE!', gettype($current)));
766 // Handle current record
767 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: current(%d)[%s]=%s', strlen($current), gettype($current), $current));
770 // If the last read block is empty, check gaps
771 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: current()=%d', strlen($current)));
772 if (empty(trim($current, chr(0)))) {
774 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Found a total of %d gaps.', count($this->gaps)));
776 // Check gaps, if the whole file is empty.
777 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->isFileGapsOnly() ...');
778 if ($this->isFileGapsOnly()) {
779 // Only gaps, so don't continue here.
780 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: File is gaps-only - EXIT!');
786 * The above call has calculated a total size of all gaps. If the
787 * percentage of gaps passes a "soft" limit and last
788 * defragmentation is to far in the past, or if a "hard" limit has
789 * reached, run defragmentation.
791 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->isDefragmentationNeeded() ...');
792 if ($this->isDefragmentationNeeded()) {
793 // Run "defragmentation"
794 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->doRunDefragmentation() ...');
795 $this->doRunDefragmentation();
799 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
803 * Reads next "block" of given bytes into $currentBlock field. THis method
804 * loads the whole file into memory when the file is just freshly
805 * initialized (only zeros in it).
808 * @throws InvalidArgumentException If a parameter is not valid
810 protected function readNextBlockByLength (int $length) {
811 // Validate parameter
812 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: this->seekPosition=%d,length=%d - CALLED!', $this->getSeekPosition(), $length));
815 throw new InvalidArgumentException(sprintf('length=%d is not valid', $length));
818 // Read possibly back-buffered bytes from previous call of next().
819 $data = $this->getBackBuffer();
822 * Read until a entry/block separator has been found. The next read
823 * "block" may not fit, so this loop will continue until the EOB or EOF
824 * has been reached whatever comes first.
826 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: this->seekPosition=%d,data()=%d', $this->getSeekPosition(), strlen($data)));
827 while ((!$this->isEndOfFileReached()) && (empty($data) || !self::isBlockSeparatorFound($data))) {
828 // Then read the next possible block
829 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: this->seekPosition=%d, calling this->read(%d) ...', $this->getSeekPosition(), $length));
830 $block = $this->read($length);
832 // Is the block empty?
833 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: block()=%d,length=%d', strlen($block), $length));
834 if (strlen($block) == 0) {
835 // Read empty block, maybe EOF
836 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: this->seekPosition=%d, block is empty, maybe EOF reached - BREAK!', $this->getSeekPosition()));
838 } elseif (empty(trim($block, chr(0)))) {
840 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: this->seekPosition=%d, calling this->markCurrentBlockAsEmpty(%d) ...', $this->getSeekPosition(), $length));
841 $this->markCurrentBlockAsEmpty($length);
844 // At this block then
848 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: this->seekPosition=%d,data()=%d', $this->getSeekPosition(), strlen($data)));
852 * Init back-buffer which is the data that has been found beyond the
855 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->initBackBuffer(), clearing this->currentBlock ...');
856 $this->initBackBuffer();
857 $this->setCurrentBlock('');
860 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: data(%d)=%s', strlen($data), $data));
861 if (empty(trim($data, chr(0)))) {
862 // Yes, maybe whole file was ...
863 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: this->seekPosition=%d, maybe empty file found - EXIT!', $this->getSeekPosition()));
868 $dataArray = explode(chr(BinaryFile::SEPARATOR_ENTRIES), $data);
870 // Left part is the actual block, right one the back-buffer data, if found
871 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: dataArray()=%d', count($dataArray)));
872 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: dataArray=%s', print_r($dataArray, true)));
873 $this->setCurrentBlock($dataArray[0]);
875 // Is back buffere data found?
876 if (isset($dataArray[1]) && !empty(trim($dataArray[1], chr(0)))) {
878 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Setting this->backBuffer=%s ...', $dataArray[1]));
879 $this->setBackBuffer($dataArray[1]);
883 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
887 * Pre-allocates file (if enabled) with some space for later faster write access.
889 * @param $type Type of the file
891 * @throws InvalidArgumentException If a parameter is empty
892 * @throws BadMethodCallException If this->stackInstance is not properly set
894 protected function preAllocateFileByTypeLength (string $type, int $minimumBlockLength) {
896 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: type=%s,minimumBlockLength=%d - CALLED!', $type, $minimumBlockLength));
899 throw new InvalidArgumentException('Parameter "type" is empty');
900 } elseif ($minimumBlockLength < 1) {
901 // Invalid block length
902 throw new InvalidArgumentException(sprintf('Parameter minimumBlockLength=%d is not valid', $minimumBlockLength));
903 } elseif (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($type . '_pre_allocate_enabled') != 'Y') {
904 // Don't continue here.
905 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Not pre-allocating file.'));
910 $fileSize = $this->getFileSize();
912 // Calulcate seek position
913 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: minimumBlockLength=%d,fileSize=%d', $minimumBlockLength, $fileSize));
914 $seekPosition = $this->getHeaderSize() + $minimumBlockLength * FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($type . '_pre_allocate_count') + $fileSize ;
916 // Now simply write a NUL there. This will pre-allocate the file.
917 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling this->writeAtPosition(%d,NUL) ...', $seekPosition));
918 $this->writeAtPosition($seekPosition, chr(0));
920 // Is the seek position zero?
921 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: fileSize=%d', $fileSize));
922 if ($fileSize == 0) {
923 // Mark file as gaps-only
924 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: Calling this->markGapsOnly(%s,%d) ...', $type, $minimumBlockLength));
925 $this->markFileGapsOnly($type, $minimumBlockLength);
927 // Analyze file structure
928 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->analyzeFileStructure() ...');
929 $this->analyzeFileStructure();
932 // Rewind seek position
933 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: Calling this->rewind() ...');
937 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-BINARY-FILE: EXIT!');
941 * Checks wether the current entry is valid (not at the end of the file).
942 * This method will return true if an emptied (nulled) entry has been found.
944 * @return $isValid Whether the next entry is valid
945 * @throws InvalidArgumentException If a parameter is not valid
947 protected function isValidByLength (int $length) {
948 // Validate parameter
949 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: length=%d - CALLED!', $length));
952 throw new InvalidArgumentException(sprintf('Parameter length=%d is not valid', $length));
955 // Get current seek position
956 $seekPosition = $this->determineSeekPosition();
958 // Then try to read it
959 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%d', $seekPosition));
960 $data = $this->read($length);
962 // If some bytes could be read, all is fine
963 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: data[%s]()=%d', gettype($data), strlen($data)));
964 $isValid = ((is_string($data)) && (strlen($data) > 0));
967 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: isValid=%d', intval($isValid)));
968 $headerSize = $this->getHeaderSize();
970 // Is the seek position at or beyond the header?
971 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%d,headerSize=%d', $seekPosition, $headerSize));
972 if ($seekPosition >= $headerSize) {
973 // Seek back to old position
974 $isValid = ($isValid && $this->seek($seekPosition) === 0);
976 // Seek directly behind the header
977 $isValid = ($isValid && $this->seek($headerSize) === 0);
981 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: isValid=%d - EXIT!', intval($isValid)));
986 * Reads next "block" of bytes into $currentBlock field. THis method loads
987 * the whole file into memory when the file is just freshly initialized
988 * (only zeros in it).
992 protected abstract function readNextBlock ();
995 * Reads the file header
998 * @throws LogicException If both instances are not set
1000 public abstract function readFileHeader ();
1003 * Searches for next suitable gap the given length of data can fit in
1004 * including padding bytes.
1006 * @param $length Length of raw data
1007 * @return $seekPosition Found next gap's seek position
1008 * @throws InvalidArgumentException If the parameter is not valid
1010 public function searchNextGap (int $length) {
1011 // If the file is only gaps, no need to seek
1012 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: length=%d - CALLED!', $length));
1015 throw new InvalidArgumentException(sprintf('length=%d is not valid', $length));
1016 } elseif ($this->isFileGapsOnly()) {
1018 * The first empty block is the 2nd one right after the header, so
1019 * one byte gap to the header.
1021 $seekPosition = ($this->getHeaderSize() + 2);
1024 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-BINARY-FILE: seekPosition=%d - EXIT!', $seekPosition));
1025 return $seekPosition;
1029 $this->partialStub('length=' . $length);