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