]> git.mxchange.org Git - core.git/blob - framework/main/classes/stacker/file/class_BaseFileStack.php
Continued:
[core.git] / framework / main / classes / stacker / file / class_BaseFileStack.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Stack\File;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Factory\Stack\File\FileStackIndexFactory;
7 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
8 use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
9 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
10 use Org\Mxchange\CoreFramework\Iterator\Filesystem\SeekableWritableFileIterator;
11 use Org\Mxchange\CoreFramework\Stack\BaseStacker;
12 use Org\Mxchange\CoreFramework\Stack\File\InvalidMagicException;
13 use Org\Mxchange\CoreFramework\Stack\File\StackableFile;
14 use Org\Mxchange\CoreFramework\Traits\Index\IndexableTrait;
15 use Org\Mxchange\CoreFramework\Traits\Iterator\IteratorTrait;
16 use Org\Mxchange\CoreFramework\Utils\String\StringUtils;
17
18 // Import SPL stuff
19 use \InvalidArgumentException;
20 use \SplFileInfo;
21 use \UnexpectedValueException;
22
23 /**
24  * A general file-based stack class
25  *
26  * @author              Roland Haeder <webmaster@ship-simu.org>
27  * @version             0.0.0
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
31  *
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.
36  *
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.
41  *
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/>.
44  */
45 abstract class BaseFileStack extends BaseStacker implements StackableFile {
46         // Load traits
47         use IndexableTrait;
48         use IteratorTrait;
49
50         // Exception codes
51         const EXCEPTION_BAD_MAGIC = 0xe100;
52
53         /**
54          * Minimum block length
55          */
56         private static $minimumBlockLength = 0;
57
58         /**
59          * Protected constructor
60          *
61          * @param       $className      Name of the class
62          * @return      void
63          */
64         protected function __construct (string $className) {
65                 // Call parent constructor
66                 parent::__construct($className);
67         }
68
69         /**
70          * Reads the file header
71          *
72          * @return      void
73          * @todo        To hard assertions here, better rewrite them to exceptions
74          * @throws      UnexpectedValueException        If header is not proper length
75          * @throws      InvalidMagicException   If a bad magic was found
76          */
77         public function readFileHeader () {
78                 // First rewind to beginning as the header sits at the beginning ...
79                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
80                 $this->getIteratorInstance()->rewind();
81
82                 // Then read it (see constructor for calculation)
83                 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
84                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Read %d bytes (%d wanted).', strlen($data), $this->getIteratorInstance()->getHeaderSize()));
85
86                 // Have all requested bytes been read?
87                 if (strlen($data) != $this->getIteratorInstance()->getHeaderSize()) {
88                         // Bad data length
89                         throw new UnexpectedValueException(sprintf('data(%d)=%s does not match iteratorInstance->headerSize=%d',
90                                 strlen($data),
91                                 $data,
92                                 $this->getIteratorInstance()->getHeaderSize()
93                         ));
94                 }
95
96                 // Last character must be the separator
97                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: data(-1)=%s', dechex(ord(substr($data, -1, 1)))));
98                 if (substr($data, -1, 1) !== chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)) {
99                         // Not valid separator
100                         throw new UnexpectedValueException(sprintf('data=%s does not have separator=%s at the end.',
101                                 $data,
102                                 BaseBinaryFile::SEPARATOR_HEADER_ENTRIES
103                         ));
104                 }
105
106                 // Okay, then remove it
107                 $data = substr($data, 0, -1);
108
109                 // And update seek position
110                 $this->getIteratorInstance()->updateSeekPosition();
111
112                 /*
113                  * Now split it:
114                  *
115                  * 0 => magic
116                  * 1 => total entries
117                  * 2 => current seek position
118                  */
119                 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
120
121                 // Check if the array has only 3 elements
122                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: header(%d)=%s', count($header), print_r($header, true)));
123                 if (count($header) != 3) {
124                         // Header array count is not expected
125                         throw new UnexpectedValueException(sprintf('data=%s has %d elements, expected 3',
126                                 $data,
127                                 count($header)
128                         ));
129                 } elseif ($header[0] != StackableFile::STACK_MAGIC) {
130                         // Bad magic
131                         throw new InvalidMagicException($data, self::EXCEPTION_BAD_MAGIC);
132                 }
133
134                 // Check length of count and seek position
135                 if (strlen($header[1]) != BaseBinaryFile::LENGTH_COUNT) {
136                         // Count length not valid
137                         throw new UnexpectedValueException(sprintf('header[1](%d)=%s is not expected %d length',
138                                 strlen($header[1]),
139                                 $header[1],
140                                 BaseBinaryFile::LENGTH_COUNT
141                         ));
142                 } elseif (strlen($header[1]) != BaseBinaryFile::LENGTH_POSITION) {
143                         // Position length not valid
144                         throw new UnexpectedValueException(sprintf('header[2](%d)=%s is not expected %d length',
145                                 strlen($header[1]),
146                                 $header[1],
147                                 BaseBinaryFile::LENGTH_POSITION
148                         ));
149                 }
150
151                 // Decode count and seek position
152                 $header[1] = hex2bin($header[1]);
153                 $header[2] = hex2bin($header[2]);
154
155                 // Set header here
156                 $this->getIteratorInstance()->setHeader($header);
157
158                 // Trace message
159                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: EXIT!', __METHOD__, __LINE__));
160         }
161
162         /**
163          * Flushes the file header
164          *
165          * @return      void
166          */
167         public function flushFileHeader () {
168                 // Put all informations together
169                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
170                 $header = sprintf('%s%s%s%s%s%s',
171                         // Magic
172                         StackableFile::STACK_MAGIC,
173
174                         // Separator magic<->count
175                         chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
176
177                         // Total entries (will be zero) and pad it to 20 chars
178                         str_pad(StringUtils::dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
179
180                         // Separator count<->seek position
181                         chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
182
183                         // Position (will be zero)
184                         str_pad(StringUtils::dec2hex($this->getIteratorInstance()->getSeekPosition(), 2), BaseBinaryFile::LENGTH_POSITION, '0', STR_PAD_LEFT),
185
186                         // Separator position<->entries
187                         chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
188                 );
189
190                 // Write it to disk (header is always at seek position 0)
191                 $this->getIteratorInstance()->writeData(0, $header, false);
192
193                 // Trace message
194                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: EXIT!');
195         }
196
197         /**
198          * Initializes this file-based stack.
199          *
200          * @param       $fileInfoInstance       An instance of a SplFileInfo class
201          * @param       $type           Type of this stack (e.g. url_source for URL sources)
202          * @return      void
203          * @throws      InvalidArgumentException        If a parameter is invalid
204          * @todo        Currently the stack file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole stack file.
205          */
206         protected function initFileStack (SplFileInfo $fileInfoInstance, string $type) {
207                 // Validate parameter
208                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: fileInfoInstance[%s]=%s,type=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance, $type));
209                 if (empty($type)) {
210                         // Invalid parameter
211                         throw new InvalidArgumentException('Parameter "type" is empty');
212                 }
213
214                 // Get a stack file instance
215                 $stackInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileInfoInstance, $this));
216
217                 // Get iterator instance
218                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($stackInstance));
219
220                 // Set iterator here
221                 $this->setIteratorInstance($iteratorInstance);
222
223                 // Calculate header size
224                 $this->getIteratorInstance()->setHeaderSize(
225                         strlen(StackableFile::STACK_MAGIC) +
226                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
227                         BaseBinaryFile::LENGTH_COUNT +
228                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
229                         BaseBinaryFile::LENGTH_POSITION +
230                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
231                 );
232
233                 // Init counters and gaps array
234                 $this->getIteratorInstance()->initCountersGapsArray();
235
236                 // Is the file's header initialized?
237                 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
238                         // No, then create it (which may pre-allocate the stack)
239                         $this->getIteratorInstance()->createFileHeader();
240
241                         // And pre-allocate a bit
242                         $this->getIteratorInstance()->preAllocateFile('file_stack');
243                 }
244
245                 // Load the file header
246                 $this->readFileHeader();
247
248                 // Count all entries in file
249                 $this->getIteratorInstance()->analyzeFile();
250
251                 /*
252                  * Get stack index instance. This can be used for faster
253                  * "defragmentation" and startup.
254                  */
255                 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileInfoInstance, $type);
256
257                 // And set it here
258                 $this->setIndexInstance($indexInstance);
259
260                 // Trace message
261                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: EXIT!');
262         }
263
264         /**
265          * Adds a value to given stack
266          *
267          * @param       $stackerName    Name of the stack
268          * @param       $value                  Value to add to this stacker
269          * @return      void
270          * @throws      FullStackerException    If the stack is full
271          * @throws      InvalidArgumentException        If a parameter is not valid
272          * @throws      InvalidArgumentException        Not all variable types are wanted here
273          */
274         protected function addValue (string $stackerName, $value) {
275                 // Validate parameter
276                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s,value[%s]=%s - CALLED!', $stackerName, gettype($value), print_r($value, true)));
277                 if (empty($stackerName)) {
278                         // No empty stack name
279                         throw new InvalidArgumentException('Parameter "stackerName" is empty');
280                 } elseif ($this->isStackFull($stackerName)) {
281                         // Stacker is full
282                         throw new FullStackerException([$this, $stackerName, $value], self::EXCEPTION_STACKER_IS_FULL);
283                 } elseif (is_resource($value) || is_object($value)) {
284                         // Not wanted type
285                         throw new InvalidArgumentException(sprintf('value[]=%s is not supported', gettype($value)));
286                 }
287
288                 /*
289                  * Now add the value to the file stack which returns gap position, a
290                  * hash and length of the raw data.
291                  */
292                 $data = $this->getIteratorInstance()->writeValueToFile($stackerName, $value);
293
294                 // Add the hash and gap position to the index
295                 $this->getIndexInstance()->addHashToIndex($stackerName, $data);
296
297                 // Trace message
298                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: EXIT!');
299         }
300
301         /**
302          * Get last value from named stacker
303          *
304          * @param       $stackerName    Name of the stack
305          * @return      $value                  Value of last added value
306          * @throws      InvalidArgumentException        If a parameter is not valid
307          * @throws      BadMethodCallException  If the stack is empty
308          */
309         protected function getLastValue (string $stackerName) {
310                 // Validate parameter
311                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
312                 if (empty($stackerName)) {
313                         // No empty stack name
314                         throw new InvalidArgumentException('Parameter "stackerName" is empty');
315                 } elseif ($this->isStackEmpty($stackerName)) {
316                         // Throw an exception
317                         throw new BadMethodCallException([$this, $stackerName], self::EXCEPTION_STACKER_IS_EMPTY);
318                 }
319
320                 // Now get the last value
321                 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
322                 $value = NULL;
323
324                 // Return it
325                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: value[]=%s - EXIT!', gettype($value)));
326                 return $value;
327         }
328
329         /**
330          * Get first value from named stacker
331          *
332          * @param       $stackerName    Name of the stack
333          * @return      $value                  Value of last added value
334          * @throws      InvalidArgumentException        If a parameter is not valid
335          * @throws      BadMethodCallException  If the stack is empty
336          */
337         protected function getFirstValue (string $stackerName) {
338                 // Validate parameter
339                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
340                 if (empty($stackerName)) {
341                         // No empty stack name
342                         throw new InvalidArgumentException('Parameter "stackerName" is empty');
343                 } elseif ($this->isStackEmpty($stackerName)) {
344                         // Throw an exception
345                         throw new BadMethodCallException([$this, $stackerName], self::EXCEPTION_STACKER_IS_EMPTY);
346                 }
347
348                 // Now get the first value
349                 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
350                 $value = NULL;
351
352                 // Return it
353                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: value[]=%s - EXIT!', gettype($value)));
354                 return $value;
355         }
356
357         /**
358          * "Pops" last entry from stack
359          *
360          * @param       $stackerName    Name of the stack
361          * @return      $value                  Value "poped" from array
362          * @throws      InvalidArgumentException        If a parameter is not valid
363          * @throws      BadMethodCallException  If the stack is empty
364          */
365         protected function popLast (string $stackerName) {
366                 // Validate parameter
367                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
368                 if (empty($stackerName)) {
369                         // No empty stack name
370                         throw new InvalidArgumentException('Parameter "stackerName" is empty');
371                 } elseif ($this->isStackEmpty($stackerName)) {
372                         // Throw an exception
373                         throw new BadMethodCallException([$this, $stackerName], self::EXCEPTION_STACKER_IS_EMPTY);
374                 }
375
376                 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
377                 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
378                 return NULL;
379         }
380
381         /**
382          * "Pops" first entry from stack
383          *
384          * @param       $stackerName    Name of the stack
385          * @return      $value                  Value "shifted" from array
386          * @throws      InvalidArgumentException        If a parameter is not valid
387          * @throws      BadMethodCallException  If the named stacker is empty
388          */
389         protected function popFirst (string $stackerName) {
390                 // Validate parameter
391                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
392                 if (empty($stackerName)) {
393                         // No empty stack name
394                         throw new InvalidArgumentException('Parameter "stackerName" is empty');
395                 } elseif ($this->isStackEmpty($stackerName)) {
396                         // Throw an exception
397                         throw new BadMethodCallException([$this, $stackerName], self::EXCEPTION_STACKER_IS_EMPTY);
398                 }
399
400                 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
401                 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
402                 return NULL;
403         }
404
405         /**
406          * Checks whether the given stack is full
407          *
408          * @param       $stackerName    Name of the stack
409          * @return      $isFull                 Whether the stack is full
410          * @throws      InvalidArgumentException        If a parameter is not valid
411          */
412         protected function isStackFull (string $stackerName) {
413                 // Validate parameter
414                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
415                 if (empty($stackerName)) {
416                         // No empty stack name
417                         throw new InvalidArgumentException('Parameter "stackerName" is empty');
418                 }
419
420                 // @TODO Please implement this, returning false
421                 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
422                 $isFull = false;
423
424                 // Return result
425                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: isFull=%d - EXIT!', intval($isFull)));
426                 return $isFull;
427         }
428
429         /**
430          * Checks whether the given stack is empty
431          *
432          * @param       $stackerName            Name of the stack
433          * @return      $isEmpty                        Whether the stack is empty
434          * @throws      InvalidArgumentException        If a parameter is not valid
435          * @throws      BadMethodCallException  If given stack is missing
436          */
437         public function isStackEmpty (string $stackerName) {
438                 // Validate parameter
439                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
440                 if (empty($stackerName)) {
441                         // No empty stack name
442                         throw new InvalidArgumentException('Parameter "stackerName" is empty');
443                 }
444
445                 // So, is the stack empty?
446                 $isEmpty = (($this->getStackCount($stackerName)) == 0);
447
448                 // Return result
449                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: isEmpty=%d - EXIT!', intval($isEmpty)));
450                 return $isEmpty;
451         }
452
453         /**
454          * Initializes given stacker
455          *
456          * @param       $stackerName    Name of the stack
457          * @param       $forceReInit    Force re-initialization
458          * @return      void
459          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
460          */
461         public function initStack (string $stackerName, bool $forceReInit = false) {
462                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
463         }
464
465         /**
466          * Initializes all stacks
467          *
468          * @return      void
469          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
470          */
471         public function initStacks (array $stacks, bool $forceReInit = false) {
472                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
473         }
474
475         /**
476          * Checks whether the given stack is initialized (set in array $stackers)
477          *
478          * @param       $stackerName    Name of the stack
479          * @return      $isInitialized  Whether the stack is initialized
480          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
481          */
482         public function isStackInitialized (string $stackerName) {
483                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
484         }
485
486         /**
487          * Determines whether the EOF has been reached
488          *
489          * @return      $isEndOfFileReached             Whether the EOF has been reached
490          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
491          */
492         public function isEndOfFileReached () {
493                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
494         }
495
496         /**
497          * Getter for size of given stack (array count)
498          *
499          * @param       $stackerName    Name of the stack
500          * @return      $count                  Size of stack (array count)
501          */
502         public function getStackCount (string $stackerName) {
503                 // Now, simply return the found count value, this must be up-to-date then!
504                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
505                 $count = $this->getIteratorInstance()->getCounter();
506
507                 // Return count
508                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: count=%d - EXIT!', $count));
509                 return $count;
510         }
511
512         /**
513          * Calculates minimum length for one entry/block
514          *
515          * @return      $length         Minimum length for one entry/block
516          */
517         public function calculateMinimumBlockLength () {
518                 // Is the value "cached"?
519                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
520                 if (self::$minimumBlockLength == 0) {
521                         // Calulcate it
522                         self::$minimumBlockLength =
523                                 // Length of entry group
524                                 BaseBinaryFile::LENGTH_GROUP + strlen(chr(BaseBinaryFile::SEPARATOR_GROUP_HASH)) +
525                                 // Hash + value
526                                 self::getHashLength() + strlen(chr(BaseBinaryFile::SEPARATOR_HASH_VALUE)) + 1 +
527                                 // Final separator
528                                 strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
529                 }
530
531                 // Return it
532                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: self::minimumBlockLength=%d - EXIT!', self::$minimumBlockLength));
533                 return self::$minimumBlockLength;
534         }
535
536         /**
537          * Initializes counter for valid entries, arrays for damaged entries and
538          * an array for gap seek positions. If you call this method on your own,
539          * please re-analyze the file structure. So you are better to call
540          * analyzeFile() instead of this method.
541          *
542          * @return      void
543          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
544          */
545         public function initCountersGapsArray () {
546                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
547         }
548
549         /**
550          * Getter for header size
551          *
552          * @return      $totalEntries   Size of file header
553          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
554          */
555         public final function getHeaderSize () {
556                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
557         }
558
559         /**
560          * Setter for header size
561          *
562          * @param       $headerSize             Size of file header
563          * @return      void
564          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
565          */
566         public final function setHeaderSize (int $headerSize) {
567                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
568         }
569
570         /**
571          * Getter for header array
572          *
573          * @return      $totalEntries   Size of file header
574          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
575          */
576         public final function getHeader () {
577                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
578         }
579
580         /**
581          * Setter for header
582          *
583          * @param       $header         Array for a file header
584          * @return      void
585          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
586          */
587         public final function setHeader (array $header) {
588                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
589         }
590
591         /**
592          * Updates seekPosition attribute from file to avoid to much access on file.
593          *
594          * @return      void
595          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
596          */
597         public function updateSeekPosition () {
598                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
599         }
600
601         /**
602          * Getter for total entries
603          *
604          * @return      $totalEntries   Total entries in this file
605          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
606          */
607         public final function getCounter () {
608                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
609         }
610
611         /**
612          * Writes data at given position
613          *
614          * @param       $seekPosition   Seek position
615          * @param       $data                   Data to be written
616          * @param       $flushHeader    Whether to flush the header (default: flush)
617          * @return      void
618          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
619          */
620         public function writeData (int $seekPosition, string $data, bool $flushHeader = true) {
621                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: seekPosition=%s,data[]=%s,flushHeader=%d', $seekPosition, gettype($data), intval($flushHeader)));
622                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
623         }
624
625         /**
626          * Writes given value to the file and returns a hash and gap position for it
627          *
628          * @param       $groupId        Group identifier
629          * @param       $value          Value to be added to the stack
630          * @return      $data           Hash and gap position
631          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
632          */
633         public function writeValueToFile (string $groupId, $value) {
634                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: groupId=%s,value[%s]=%s', $groupId, gettype($value), print_r($value, true)));
635                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
636         }
637
638         /**
639          * Searches for next suitable gap the given length of data can fit in
640          * including padding bytes.
641          *
642          * @param       $length                 Length of raw data
643          * @return      $seekPosition   Found next gap's seek position
644          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
645          */
646         public function searchNextGap (int $length) {
647                 // Not supported here
648                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: length=%d - CALLED!', $length));
649                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
650         }
651
652         /**
653          * "Getter" for file size
654          *
655          * @return      $fileSize       Size of currently loaded file
656          */
657         public function getFileSize () {
658                 // Call iterator's method
659                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
660                 $size = $this->getIteratorInstance()->getFileSize();
661
662                 // Return size
663                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: size=%d - EXIT!', $size));
664                 return $size;
665         }
666
667         /**
668          * Writes given raw data to the file and returns a gap position and length
669          *
670          * @param       $groupId        Group identifier
671          * @param       $hash           Hash from encoded value
672          * @param       $encoded        Encoded value to be written to the file
673          * @return      $data           Gap position and length of the raw data
674          */
675         public function writeDataToFreeGap (string $groupId, string $hash, string $encoded) {
676                 // Raw data been written to the file
677                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: groupId=%s,hash=%s,encoded()=%d - CALLED!', $groupId, $hash, strlen($encoded)));
678                 $rawData = sprintf('%s%s%s%s%s',
679                         $groupId,
680                         BaseBinaryFile::SEPARATOR_GROUP_HASH,
681                         hex2bin($hash),
682                         BaseBinaryFile::SEPARATOR_HASH_VALUE,
683                         $encoded
684                 );
685
686                 // Search for next free gap
687                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: groupId=%s,hash=%s,rawData()=%d', $groupId, $hash, strlen($rawData)));
688                 $gapPosition = $this->getIteratorInstance()->searchNextGap(strlen($rawData));
689
690                 // Gap position cannot be smaller than header length + 1
691                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: gapPosition=%d', $gapPosition));
692                 if ($gapPosition <= $this->getIteratorInstance()->getHeaderSize()) {
693                         // Improper gap position
694                         throw new UnexpectedValueException(sprintf('gapPosition[%s]=%d is not larger than headerSize=%d',
695                                 gettype($gapPosition),
696                                 $gapPosition,
697                                 $this->getIteratorInstance()->getHeaderSize()
698                         ));
699                 }
700
701                 // Then write the data at that gap
702                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: groupId=%s,hash=%s,gapPosition=%s', $groupId, $hash, $gapPosition));
703                 $this->getIteratorInstance()->writeData($gapPosition, $rawData);
704
705                 // Return gap position, hash and length of raw data
706                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: groupId=%s,hash=%s,rawData()=%d - EXIT!', $groupId, $hash, strlen($rawData)));
707                 return [
708                         self::ARRAY_NAME_GAP_POSITION => $gapPosition,
709                         self::ARRAY_NAME_HASH         => $hash,
710                         self::ARRAY_NAME_DATA_LENGTH  => strlen($rawData),
711                 ];
712         }
713
714 }