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