Some updates:
[core.git] / framework / main / classes / file_directories / binary / class_BaseBinaryFile.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Filesystem\File;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
7 use Org\Mxchange\CoreFramework\Filesystem\Block;
8 use Org\Mxchange\CoreFramework\Filesystem\Block\CalculatableBlock;
9 use Org\Mxchange\CoreFramework\Filesystem\File\BaseAbstractFile;
10
11 // Import SPL stuff
12 use \SplFileInfo;
13
14 /**
15  * A general binary file class
16  *
17  * @author              Roland Haeder <webmaster@ship-simu.org>
18  * @version             0.0.0
19 <<<<<<< HEAD:framework/main/classes/file_directories/binary/class_BaseBinaryFile.php
20  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
21 =======
22  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
23 >>>>>>> Some updates::inc/main/classes/file_directories/binary/class_BaseBinaryFile.php
24  * @license             GNU GPL 3.0 or any newer version
25  * @link                http://www.ship-simu.org
26  *
27  * This program is free software: you can redistribute it and/or modify
28  * it under the terms of the GNU General Public License as published by
29  * the Free Software Foundation, either version 3 of the License, or
30  * (at your option) any later version.
31  *
32  * This program is distributed in the hope that it will be useful,
33  * but WITHOUT ANY WARRANTY; without even the implied warranty of
34  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
35  * GNU General Public License for more details.
36  *
37  * You should have received a copy of the GNU General Public License
38  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
39  */
40 abstract class BaseBinaryFile extends BaseAbstractFile {
41         /**
42          * Separator for header data
43          */
44         const SEPARATOR_HEADER_DATA = 0x01;
45
46         /**
47          * Separator header->entries
48          */
49         const SEPARATOR_HEADER_ENTRIES = 0x02;
50
51         /**
52          * Separator group->hash
53          */
54         const SEPARATOR_GROUP_HASH = 0x03;
55
56         /**
57          * Separator hash->value
58          */
59         const SEPARATOR_HASH_VALUE = 0x04;
60
61         /**
62          * Separator entry->entry
63          */
64         const SEPARATOR_ENTRIES = 0x05;
65
66         /**
67          * Separator type->position
68          */
69         const SEPARATOR_TYPE_POSITION = 0x06;
70
71         /**
72          * Length of count
73          */
74         const LENGTH_COUNT = 20;
75
76         /**
77          * Length of position
78          */
79         const LENGTH_POSITION = 20;
80
81         /**
82          * Length of group
83          */
84         const LENGTH_GROUP = 10;
85
86         /**
87          * Maximum length of entry type
88          */
89         const LENGTH_TYPE = 20;
90
91         //***** Array elements for 'gaps' array *****
92
93         /**
94          * Start of gap
95          */
96         const GAPS_INDEX_START = 'start';
97
98         /**
99          * End of gap
100          */
101         const GAPS_INDEX_END = 'end';
102
103         /**
104          * Current seek position
105          */
106         private $seekPosition = 0;
107
108         /**
109          * Size of header
110          */
111         private $headerSize = 0;
112
113         /**
114          * File header
115          */
116         private $header = array();
117
118         /**
119          * Seek positions for gaps ("fragmentation")
120          */
121         private $gaps = array();
122
123         /**
124          * Seek positions for damaged entries (e.g. mismatching hash sum, ...)
125          */
126         private $damagedEntries = array();
127
128         /**
129          * Back-buffer
130          */
131         private $backBuffer = '';
132
133         /**
134          * Currently loaded block (will be returned by current())
135          */
136         private $currentBlock = '';
137
138         /**
139          * Protected constructor
140          *
141          * @param       $className      Name of the class
142          * @return      void
143          */
144         protected function __construct ($className) {
145                 // Call parent constructor
146                 parent::__construct($className);
147
148                 // Init counters and gaps array
149                 $this->initCountersGapsArray();
150         }
151
152         /**
153          * Checks whether the abstracted file only contains gaps by counting all
154          * gaps' bytes together and compare it to total length.
155          *
156          * @return      $isGapsOnly             Whether the abstracted file only contains gaps
157          */
158         private function isFileOnlyGaps () {
159                 // First/last gap found?
160                 /* Only for debugging
161                 if (isset($this->gaps[0])) {
162                         // Output first and last gap
163                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] this->gaps[0]=%s,this->gaps[%s]=%s', __METHOD__, __LINE__, print_r($this->gaps[0], true), (count($this->gaps) - 1), print_r($this->gaps[count($this->gaps) - 1], true)));
164                 } // END - if
165                 */
166
167                 // Now count every gap
168                 $gapsSize = 0;
169                 foreach ($this->gaps as $gap) {
170                         // Calculate size of found gap: end-start including both
171                         $gapsSize += ($gap[self::GAPS_INDEX_END] - $gap[self::GAPS_INDEX_START]);
172                 } // END - if
173
174                 // Debug output
175                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] gapsSize=%s,this->headerSize=%s', __METHOD__, __LINE__, $gapsSize, $this->getHeaderSize()));
176
177                 // Total gap size + header size must be same as file size
178                 $isGapsOnly = (($this->getHeaderSize() + $gapsSize) == $this->getFileSize());
179
180                 // Return status
181                 return $isGapsOnly;
182         }
183
184         /**
185          * Initializes counter for valid entries, arrays for damaged entries and
186          * an array for gap seek positions. If you call this method on your own,
187          * please re-analyze the file structure. So you are better to call
188          * analyzeFile() instead of this method.
189          *
190          * @return      void
191          */
192         public function initCountersGapsArray () {
193                 // Init counter and seek position
194                 $this->setCounter(0);
195                 $this->setSeekPosition(0);
196
197                 // Init arrays
198                 $this->gaps = array();
199                 $this->damagedEntries = array();
200         }
201
202         /**
203          * Getter for header size
204          *
205          * @return      $totalEntries   Size of file header
206          */
207         public final function getHeaderSize () {
208                 // Get it
209                 return $this->headerSize;
210         }
211
212         /**
213          * Setter for header size
214          *
215          * @param       $headerSize             Size of file header
216          * @return      void
217          */
218         public final function setHeaderSize ($headerSize) {
219                 // Set it
220                 $this->headerSize = $headerSize;
221         }
222
223         /**
224          * Getter for header array
225          *
226          * @return      $totalEntries   Size of file header
227          */
228         public final function getHeader () {
229                 // Get it
230                 return $this->header;
231         }
232
233         /**
234          * Setter for header
235          *
236          * @param       $header         Array for a file header
237          * @return      void
238          */
239         public final function setHeader (array $header) {
240                 // Set it
241                 $this->header = $header;
242         }
243
244         /**
245          * Getter for seek position
246          *
247          * @return      $seekPosition   Current seek position (stored here in object)
248          */
249         public final function getSeekPosition () {
250                 // Get it
251                 return $this->seekPosition;
252         }
253
254         /**
255          * Setter for seek position
256          *
257          * @param       $seekPosition   Current seek position (stored here in object)
258          * @return      void
259          */
260         protected final function setSeekPosition ($seekPosition) {
261                 // And set it
262                 $this->seekPosition = $seekPosition;
263         }
264
265         /**
266          * Updates seekPosition attribute from file to avoid to much access on file.
267          *
268          * @return      void
269          */
270         public function updateSeekPosition () {
271                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
272
273                 // Get key (= seek position)
274                 $seekPosition = $this->key();
275                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Setting seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
276
277                 // And set it here
278                 $this->setSeekPosition($seekPosition);
279
280                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
281         }
282
283         /**
284          * Seeks to beginning of file, updates seek position in this object and
285          * flushes the header.
286          *
287          * @return      void
288          */
289         protected function rewindUpdateSeekPosition () {
290                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
291
292                 // flushFileHeader must be callable
293                 assert(is_callable(array($this, 'flushFileHeader')));
294
295                 // Seek to beginning of file
296                 $this->rewind();
297
298                 // And update seek position ...
299                 $this->updateSeekPosition();
300
301                 // ... to write it back into the file
302                 $this->flushFileHeader();
303
304                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
305         }
306
307         /**
308          * Seeks to old position
309          *
310          * @return      void
311          */
312         protected function seekToOldPosition () {
313                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
314
315                 // Seek to currently ("old") saved position
316                 $this->seek($this->getSeekPosition());
317
318                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
319         }
320
321         /**
322          * Checks whether the block separator has been found
323          *
324          * @param       $str            String to look in
325          * @return      $isFound        Whether the block separator has been found
326          */
327         public static function isBlockSeparatorFound ($str) {
328                 // Determine it
329                 $isFound = (strpos($str, chr(self::SEPARATOR_ENTRIES)) !== false);
330
331                 // Return result
332                 return $isFound;
333         }
334
335         /**
336          * Initializes the back-buffer by setting it to an empty string.
337          *
338          * @return      void
339          */
340         private function initBackBuffer () {
341                 // Simply call the setter
342                 $this->setBackBuffer('');
343         }
344
345         /**
346          * Setter for backBuffer field
347          *
348          * @param       $backBuffer             Characters to "store" in back-buffer
349          * @return      void
350          */
351         private function setBackBuffer ($backBuffer) {
352                 // Cast to string (so no arrays or objects)
353                 $backBuffer = (string) $backBuffer;
354
355                 // ... and set it
356                 $this->backBuffer = $backBuffer;
357         }
358
359         /**
360          * Getter for backBuffer field
361          *
362          * @return      $backBuffer             Characters "stored" in back-buffer
363          */
364         private function getBackBuffer () {
365                 return $this->backBuffer;
366         }
367
368         /**
369          * Setter for currentBlock field
370          *
371          * @param       $currentBlock           Characters to set a currently loaded block
372          * @return      void
373          */
374         private function setCurrentBlock ($currentBlock) {
375                 // Cast to string (so no arrays or objects)
376                 $currentBlock = (string) $currentBlock;
377
378                 // ... and set it
379                 $this->currentBlock = $currentBlock;
380         }
381
382         /**
383          * Gets currently read data
384          *
385          * @return      $current        Currently read data
386          */
387         public function getCurrentBlock () {
388                 // Return it
389                 return $this->currentBlock;
390         }
391
392         /**
393          * Initializes this file class
394          *
395          * @param       $infoInstance   An instance of a SplFileInfo class
396          * @return      void
397          */
398         protected function initFile (SplFileInfo $infoInstance) {
399                 // Get a file i/o pointer instance
400                 $pointerInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_output_class', array($infoInstance));
401
402                 // ... and set it here
403                 $this->setPointerInstance($pointerInstance);
404         }
405
406         /**
407          * Writes data at given position
408          *
409          * @param       $seekPosition   Seek position
410          * @param       $data                   Data to be written
411          * @param       $flushHeader    Whether to flush the header (default: flush)
412          * @return      void
413          */
414         public function writeData ($seekPosition, $data, $flushHeader = true) {
415                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data()=%d - CALLED!', __METHOD__, __LINE__, $seekPosition, strlen($data)));
416
417                 // Write data at given position
418                 $this->getPointerInstance()->writeAtPosition($seekPosition, $data);
419
420                 // Increment counter
421                 $this->incrementCounter();
422
423                 // Update seek position
424                 $this->updateSeekPosition();
425
426                 // Flush the header?
427                 if ($flushHeader === true) {
428                         // Flush header
429                         $this->flushFileHeader();
430
431                         // Seek to old position
432                         $this->seekToOldPosition();
433                 } // END - if
434
435                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
436         }
437
438         /**
439          * Marks the currently loaded block as empty (with length of the block)
440          *
441          * @param       $length         Length of the block
442          * @return      void
443          */
444         protected function markCurrentBlockAsEmpty ($length) {
445                 // Get current seek position
446                 $currentPosition = $this->key();
447
448                 // Now add it as gap entry
449                 array_push($this->gaps, array(
450                         self::GAPS_INDEX_START  => ($currentPosition - $length),
451                         self::GAPS_INDEX_END    => $currentPosition,
452                 ));
453         }
454
455         /**
456          * Checks whether the file header is initialized
457          *
458          * @return      $isInitialized  Whether the file header is initialized
459          */
460         public function isFileHeaderInitialized () {
461                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
462
463                 // Default is not initialized
464                 $isInitialized = false;
465
466                 // Is the file initialized?
467                 if ($this->isFileInitialized()) {
468                         // Some bytes has been written, so rewind to start of it.
469                         $rewindStatus = $this->rewind();
470                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] rewindStatus=%s', __METHOD__, __LINE__, $rewindStatus));
471
472                         // Is the rewind() call successfull?
473                         if ($rewindStatus != 1) {
474                                 // Something bad happened
475                                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Could not rewind().', __METHOD__, __LINE__));
476                         } // END - if
477
478                         // Read file header
479                         $this->readFileHeader();
480
481                         // The above method does already check the header
482                         $isInitialized = true;
483                 } // END - if
484
485                 // Return result
486                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
487                 return $isInitialized;
488         }
489
490         /**
491          * Checks whether the assigned file has been initialized
492          *
493          * @return      $isInitialized          Whether the file's size is zero
494          */
495         public function isFileInitialized () {
496                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
497
498                 // Get it from iterator which holds the pointer instance. If false is returned
499                 $fileSize = $this->size();
500                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] fileSize=%s', __METHOD__, __LINE__, $fileSize));
501
502                 /*
503                  * The returned file size should not be false or NULL as this means
504                  * that the pointer class does not work correctly.
505                  */
506                 assert(is_int($fileSize));
507
508                 // Is more than 0 returned?
509                 $isInitialized = ($fileSize > 0);
510
511                 // Return result
512                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
513                 return $isInitialized;
514         }
515
516         /**
517          * Creates the assigned file
518          *
519          * @return      void
520          */
521         public function createFileHeader () {
522                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
523
524                 // The file's header should not be initialized here
525                 assert(!$this->isFileHeaderInitialized());
526
527                 // Simple flush file header which will create it.
528                 $this->flushFileHeader();
529
530                 // Rewind seek position (to beginning of file) and update/flush file header
531                 $this->rewindUpdateSeekPosition();
532
533                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
534         }
535
536         /**
537          * Pre-allocates file (if enabled) with some space for later faster write access.
538          *
539          * @param       $type   Type of the file
540          * @return      void
541          */
542         public function preAllocateFile ($type) {
543                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
544
545                 // Is it enabled?
546                 if ($this->getConfigInstance()->getConfigEntry($type . '_pre_allocate_enabled') != 'Y') {
547                         // Not enabled
548                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Not pre-allocating file.', __METHOD__, __LINE__));
549
550                         // Don't continue here.
551                         return;
552                 } // END - if
553
554                 // Message to user
555                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Pre-allocating file ...', __METHOD__, __LINE__));
556
557                 // Calculate minimum length for one entry
558                 $minLengthEntry = $this->getBlockInstance()->calculateMinimumBlockLength();
559                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] minLengthEntry=%s', __METHOD__, __LINE__, $minLengthEntry));
560
561                 // Calulcate seek position
562                 $seekPosition = $minLengthEntry * $this->getConfigInstance()->getConfigEntry($type . '_pre_allocate_count');
563                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
564
565                 // Now simply write a NUL there. This will pre-allocate the file.
566                 $this->writeData($seekPosition, chr(0));
567
568                 // Rewind seek position (to beginning of file) and update/flush file header
569                 $this->rewindUpdateSeekPosition();
570
571                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
572         }
573
574         /**
575          * Determines seek position
576          *
577          * @return      $seekPosition   Current seek position
578          */
579         public function determineSeekPosition () {
580                 // Call pointer instance
581                 return $this->getPointerInstance()->determineSeekPosition();
582         }
583
584         /**
585          * Seek to given offset (default) or other possibilities as fseek() gives.
586          *
587          * @param       $offset         Offset to seek to (or used as "base" for other seeks)
588          * @param       $whence         Added to offset (default: only use offset to seek to)
589          * @return      $status         Status of file seek: 0 = success, -1 = failed
590          */
591         public function seek ($offset, $whence = SEEK_SET) {
592                 // Call pointer instance
593                 return $this->getPointerInstance()->seek($offset, $whence);
594         }
595
596         /**
597          * Reads given amount of bytes from file.
598          *
599          * @param       $bytes  Amount of bytes to read
600          * @return      $data   Data read from file
601          */
602         public function read ($bytes = NULL) {
603                 // $bytes shall be integer
604                 assert(is_int($bytes));
605
606                 // Call pointer instance
607                 return $this->getPointerInstance()->read($bytes);
608         }
609
610         /**
611          * Rewinds to the beginning of the file
612          *
613          * @return      $status         Status of this operation
614          */
615         public function rewind () {
616                 // Call pointer instance
617                 return $this->getPointerInstance()->rewind();
618         }
619
620         /**
621          * Analyzes entries in index file. This will count all found (and valid)
622          * entries, mark invalid as damaged and count gaps ("fragmentation"). If
623          * only gaps are found, the file is considered as "virgin" (no entries).
624          *
625          * @return      void
626          */
627         public function analyzeFile () {
628                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
629
630                 // Make sure the file is initialized
631                 assert($this->isFileInitialized());
632
633                 // Init counters and gaps array
634                 $this->initCountersGapsArray();
635
636                 // Output message (as this may take some time)
637                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Analyzing file structure ... (this may take some time)', __METHOD__, __LINE__));
638
639                 // First rewind to the begining
640                 $this->rewind();
641
642                 // Then try to load all entries
643                 while ($this->valid()) {
644                         // Go to next entry
645                         $this->next();
646
647                         // Get current entry
648                         $current = $this->getCurrentBlock();
649
650                         /*
651                          * If the block is empty, maybe the whole file is? This could mean
652                          * that the file has been pre-allocated.
653                          */
654                         if (empty($current)) {
655                                 // Then skip this part
656                                 continue;
657                         } // END - if
658
659                         // Debug message
660                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] current()=%d', __METHOD__, __LINE__, strlen($current)));
661                 } // END - while
662
663                 // If the last read block is empty, check gaps
664                 if (empty($current)) {
665                         // Output message
666                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Found a total of %s gaps.', __METHOD__, __LINE__, count($this->gaps)));
667
668                         // Check gaps, if the whole file is empty.
669                         if ($this->isFileOnlyGaps()) {
670                                 // Only gaps, so don't continue here.
671                                 return;
672                         } // END - if
673
674                         /*
675                          * The above call has calculated a total size of all gaps. If the
676                          * percentage of gaps passes a "soft" limit and last
677                          * defragmentation is to far in the past, or if a "hard" limit has
678                          * reached, run defragmentation.
679                          */
680                         if ($this->isDefragmentationNeeded()) {
681                                 // Run "defragmentation"
682                                 $this->doRunDefragmentation();
683                         } // END - if
684                 } // END - if
685                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
686         }
687
688         /**
689          * Advances to next "block" of bytes
690          *
691          * @return      void
692          */
693         public function next () {
694                 // Is there nothing to read?
695                 if (!$this->valid()) {
696                         // Nothing to read
697                         return;
698                 } // END - if
699
700                 // Debug message
701                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d] key()=%d', __FUNCTION__, __LINE__, $this->key()));
702
703                 // Make sure the block instance is set
704                 assert($this->getBlockInstance() instanceof CalculatableBlock);
705
706                 // First calculate minimum block length
707                 $length = $this->getBlockInstance()->calculateMinimumBlockLength();
708                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d] length=%s', __FUNCTION__, __LINE__, $length));
709
710                 // Short be more than zero!
711                 assert($length > 0);
712
713                 // Read possibly back-buffered bytes from previous call of next().
714                 $data = $this->getBackBuffer();
715
716                 /*
717                  * Read until a entry/block separator has been found. The next read
718                  * "block" may not fit, so this loop will continue until the EOB or EOF
719                  * has been reached whatever comes first.
720                  */
721                 while ((!$this->isEndOfFileReached()) && (!self::isBlockSeparatorFound($data))) {
722                         // Then read the next possible block
723                         $block = $this->read($length);
724
725                         // Debug message
726                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d] block()=%d,length=%s', __FUNCTION__, __LINE__, strlen($block), $length));
727
728                         // Is it all empty?
729                         if (strlen(trim($block)) == 0) {
730                                 // Mark this block as empty
731                                 $this->markCurrentBlockAsEmpty(strlen($block));
732
733                                 // Skip to next block
734                                 continue;
735                         } // END - if
736
737                         // At this block then
738                         $data .= $block;
739
740                         // A debug message
741                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d] data()=%d', __FUNCTION__, __LINE__, strlen($data)));
742                 } // END - while
743
744                 // EOF reached?
745                 if ($this->isEndOfFileReached()) {
746                         // Set whole data as current read block
747                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Calling setCurrentBlock(' . strlen($data) . ') ...');
748                         $this->setCurrentBlock($data);
749
750                         // Then abort here silently
751                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('EOF reached.');
752                         return;
753                 } // END - if
754
755                 /*
756                  * Init back-buffer which is the data that has been found beyond the
757                  * separator.
758                  */
759                 $this->initBackBuffer();
760
761                 // Separate data
762                 $dataArray = explode(chr(self::SEPARATOR_ENTRIES), $data);
763
764                 // This array must contain two elements
765                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('dataArray=' . print_r($dataArray, true));
766                 assert(count($dataArray) == 2);
767
768                 // Left part is the actual block, right one the back-buffer data
769                 $this->setCurrentBlock($dataArray[0]);
770                 $this->setBackBuffer($dataArray[1]);
771         }
772
773         /**
774          * Checks wether the current entry is valid (not at the end of the file).
775          * This method will return true if an emptied (nulled) entry has been found.
776          *
777          * @return      $isValid        Whether the next entry is valid
778          */
779         public function valid () {
780                 // Make sure the block instance is set
781                 assert($this->getBlockInstance() instanceof Block);
782
783                 // First calculate minimum block length
784                 $length = $this->getBlockInstance()->calculateMinimumBlockLength();
785
786                 // Short be more than zero!
787                 assert($length > 0);
788
789                 // Get current seek position
790                 $seekPosition = $this->key();
791
792                 // Then try to read it
793                 $data = $this->read($length);
794
795                 // If some bytes could be read, all is fine
796                 $isValid = ((is_string($data)) && (strlen($data) > 0));
797
798                 // Get header size
799                 $headerSize = $this->getHeaderSize();
800
801                 // Is the seek position at or beyond the header?
802                 if ($seekPosition >= $headerSize) {
803                         // Seek back to old position
804                         $this->seek($seekPosition);
805                 } else {
806                         // Seek directly behind the header
807                         $this->seek($headerSize);
808                 }
809
810                 // Return result
811                 return $isValid;
812         }
813
814         /**
815          * Gets current seek position ("key").
816          *
817          * @return      $key    Current key in iteration
818          */
819         public function key () {
820                 // Call pointer instance
821                 return $this->getPointerInstance()->determineSeekPosition();
822         }
823
824         /**
825          * Reads the file header
826          *
827          * @return      void
828          */
829         public function readFileHeader () {
830                 // Make sure the block instance is set
831                 assert($this->getBlockInstance() instanceof Block);
832
833                 // Call block instance
834                 $this->getBlockInstance()->readFileHeader();
835         }
836
837         /**
838          * Flushes the file header
839          *
840          * @return      void
841          */
842         public function flushFileHeader () {
843                 // Make sure the block instance is set
844                 assert($this->getBlockInstance() instanceof Block);
845
846                 // Call block instance
847                 $this->getBlockInstance()->flushFileHeader();
848         }
849
850         /**
851          * Searches for next suitable gap the given length of data can fit in
852          * including padding bytes.
853          *
854          * @param       $length                 Length of raw data
855          * @return      $seekPosition   Found next gap's seek position
856          */
857         public function searchNextGap ($length) {
858                 // If the file is only gaps, no need to seek
859                 if ($this->isFileOnlyGaps()) {
860                         // The first empty block is the first one right after the header
861                         return ($this->getHeaderSize() + 1);
862                 } // END - if
863
864                 // @TODO Unfinished
865                 $this->partialStub('length=' . $length);
866         }
867
868 }