]> git.mxchange.org Git - core.git/blob - framework/main/classes/index/file/class_BaseFileIndex.php
16655594dacd2b3817a97cdff95bff07f218c110
[core.git] / framework / main / classes / index / file / class_BaseFileIndex.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Index\File;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
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\Index\BaseIndex;
11 use Org\Mxchange\CoreFramework\Index\Indexable;
12 use Org\Mxchange\CoreFramework\Utils\Arrays\ArrayUtils;
13 use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
14
15 // Import SPL stuff
16 use \OutOfBoundsException;
17 use \SplFileInfo;
18 use \UnexpectedValueException;
19
20 /**
21  * A general file-based index class
22  *
23  * @author              Roland Haeder <webmaster@ship-simu.org>
24  * @version             0.0.0
25  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2021 Core Developer Team
26  * @license             GNU GPL 3.0 or any newer version
27  * @link                http://www.ship-simu.org
28  *
29  * This program is free software: you can redistribute it and/or modify
30  * it under the terms of the GNU General Public License as published by
31  * the Free Software Foundation, either version 3 of the License, or
32  * (at your option) any later version.
33  *
34  * This program is distributed in the hope that it will be useful,
35  * but WITHOUT ANY WARRANTY; without even the implied warranty of
36  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37  * GNU General Public License for more details.
38  *
39  * You should have received a copy of the GNU General Public License
40  * along with this program. If not, see <http://www.gnu.org/licenses/>.
41  */
42 abstract class BaseFileIndex extends BaseIndex implements FileIndexer {
43         /**
44          * Minimum block length
45          */
46         private static $minimumBlockLength = 0;
47
48         /**
49          * Protected constructor
50          *
51          * @param       $className      Name of class
52          * @return      void
53          */
54         protected function __construct (string $className) {
55                 // Call parent constructor
56                 parent::__construct($className);
57         }
58
59         /**
60          * Reads the file header
61          *
62          * @return      void
63          * @throws      UnexpectedValueException        If header length or count of elements is invalid
64          */
65         public function readIndexHeader () {
66                 // First rewind to beginning as the header sits at the beginning ...
67                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
68                 $this->getIteratorInstance()->rewind();
69
70                 // Get header size
71                 $headerSize = $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize();
72
73                 // Then read it (see constructor for calculation)
74                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: headerSize=%d', $headerSize));
75                 $data = $this->getIteratorInstance()->getBinaryFileInstance()->read($headerSize);
76
77                 // Have all requested bytes been read?
78                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Read %d bytes (%d wanted).', strlen($data), $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()));
79                 if (strlen($data) != $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()) {
80                         // Invalid header length
81                         throw new UnexpectedValueException(sprintf('data(%d)=%s is not expected length %d',
82                                 strlen($data),
83                                 $data,
84                                 $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()
85                         ));
86                 } elseif (empty(trim($data, chr(0)))) {
87                         // Empty file header
88                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: File header is empty - EXIT!');
89                         return;
90                 } elseif (substr($data, -1, 1) != chr(BinaryFile::SEPARATOR_HEADER_ENTRIES)) {
91                         // Bad last character
92                         throw new UnexpectedValueException(sprintf('data=%s does not end with "%s"',
93                                 $data,
94                                 chr(BinaryFile::SEPARATOR_HEADER_ENTRIES)
95                         ));
96                 }
97
98                 // Okay, then remove it
99                 $data = substr($data, 0, -1);
100
101                 // And update seek position
102                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->binaryFileInstance->updateSeekPosition() ...');
103                 $this->getIteratorInstance()->getBinaryFileInstance()->updateSeekPosition();
104
105                 /*
106                  * Now split it:
107                  *
108                  * 0 => magic
109                  * 1 => total entries
110                  */
111                 $header = explode(chr(BinaryFile::SEPARATOR_HEADER_DATA), $data);
112
113                 // Map numeric entries to associative (alpha-numeric) elements
114                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: HEADER_INDEX_ELEMENT_COUNT=%d,header()=%d', BinaryFile::HEADER_INDEX_ELEMENT_COUNT, count($header)));
115                 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: header(%d)=%s', count($header), print_r($header, true)));
116                 $header = ArrayUtils::mapNumericKeysToAssociative($header, [
117                         BinaryFile::HEADER_NAME_MAGIC,
118                         BinaryFile::HEADER_NAME_TOTAL_ENTRIES,
119                 ]);
120
121                 // Check if the array has only 2 elements
122                 if (count($header) != BinaryFile::HEADER_INDEX_ELEMENT_COUNT) {
123                         // Bad header
124                         throw new UnexpectedValueException(sprintf('header()=%d is not expected value %d', count($header), BinaryFile::HEADER_INDEX_ELEMENT_COUNT));
125                 } elseif ($header[BinaryFile::HEADER_NAME_MAGIC] !== Indexable::INDEX_MAGIC) {
126                         // Magic must be in first element
127                         throw new UnexpectedValueException(sprintf('header[%s]=%s is not the expected magic (%s)', BinaryFile::HEADER_NAME_MAGIC, $header[BinaryFile::HEADER_NAME_MAGIC], Indexable::INDEX_MAGIC));
128                 } elseif (strlen($header[BinaryFile::HEADER_NAME_TOTAL_ENTRIES]) != BinaryFile::LENGTH_COUNT) {
129                         // Length of total entries not matching
130                         throw new UnexpectedValueException(sprintf('header[%s](%d)=%s does not have expected length %d', BinaryFile::HEADER_NAME_TOTAL_ENTRIES, strlen($header[BinaryFile::HEADER_NAME_TOTAL_ENTRIES]), $header[BinaryFile::HEADER_NAME_TOTAL_ENTRIES], BinaryFile::LENGTH_COUNT));
131                 }
132
133                 // Decode count
134                 $header[BinaryFile::HEADER_NAME_TOTAL_ENTRIES] = hex2bin($header[BinaryFile::HEADER_NAME_TOTAL_ENTRIES]);
135
136                 // Set it here
137                 $this->getIteratorInstance()->getBinaryFileInstance()->setHeader($header);
138
139                 // Trace message
140                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: EXIT!');
141         }
142
143         /**
144          * Flushes the file header
145          *
146          * @return      void
147          */
148         public function flushFileHeader () {
149                 // Put all informations together
150                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
151                 $header = sprintf('%s%s%s%s',
152                         // Magic
153                         Indexable::INDEX_MAGIC,
154
155                         // Separator header data
156                         chr(BinaryFile::SEPARATOR_HEADER_DATA),
157
158                         // Total entries
159                         str_pad(StringUtils::dec2hex($this->getIteratorInstance()->getBinaryFileInstance()->getCounter()), BinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
160
161                         // Separator header<->entries
162                         chr(BinaryFile::SEPARATOR_HEADER_ENTRIES)
163                 );
164
165                 // Write it to disk (header is always at seek position 0)
166                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Calling this->iteratorInstance->binaryFileInstance->writeAtPosition(0, header=%s) ...', $header));
167                 $this->getIteratorInstance()->getBinaryFileInstance()->writeAtPosition(0, $header);
168
169                 // Trace message
170                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: EXIT!');
171         }
172
173         /**
174          * Initializes this file-based index
175          *
176          * @param       $fileInfoInstance       An instance of a SplFileInfo class
177          * @return      void
178          * @todo        Currently the index file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole index file.
179          */
180         protected function initFileIndex (SplFileInfo $fileInfoInstance) {
181                 // Get a file i/o pointer instance for index file
182                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: fileInfoInstance[%s]=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance));
183                 $fileInstance = ObjectFactory::createObjectByConfiguredName('index_file_class', array($fileInfoInstance, $this));
184
185                 // Get iterator instance
186                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', [$fileInstance]);
187
188                 // Set iterator here
189                 $this->setIteratorInstance($iteratorInstance);
190
191                 // Calculate header size
192                 $headerSize = (
193                         strlen(Indexable::INDEX_MAGIC) +
194                         strlen(chr(BinaryFile::SEPARATOR_HEADER_DATA)) +
195                         BinaryFile::LENGTH_COUNT +
196                         strlen(chr(BinaryFile::SEPARATOR_HEADER_ENTRIES))
197                 );
198
199                 // Set it
200                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Setting headerSize=%d ...', $headerSize));
201                 $this->getIteratorInstance()->getBinaryFileInstance()->setHeaderSize($headerSize);
202
203                 // Init counters and gaps array
204                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->binaryFileInstance->initCountersGapsArray() ...');
205                 $this->getIteratorInstance()->getBinaryFileInstance()->initCountersGapsArray();
206
207                 // Default is not created
208                 $created = false;
209
210                 // Is the file's header initialized?
211                 if (!$this->getIteratorInstance()->getBinaryFileInstance()->isFileHeaderInitialized()) {
212                         // First pre-allocate a bit
213                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->binaryFileInstance->preAllocateFile(index) ...');
214                         $this->getIteratorInstance()->getBinaryFileInstance()->preAllocateFile('index');
215
216                         // Then write file header
217                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->binaryFileInstance->createFileHeader() ...');
218                         $this->getIteratorInstance()->getBinaryFileInstance()->createFileHeader();
219
220                         // Mark as freshly created
221                         $created = true;
222                 }
223
224                 // Load the file header
225                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->readIndexHeader() ...');
226                 $this->readIndexHeader();
227
228                 // Freshly created?
229                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: created=%d', intval($created)));
230                 if (!$created) {
231                         // Analyze file structure
232                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calling this->iteratorInstance->binaryFileInstance->analyzeFileStructure() ...');
233                         $this->getIteratorInstance()->getBinaryFileInstance()->analyzeFileStructure();
234                 }
235
236                 // Trace message
237                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: EXIT!');
238         }
239
240         /**
241          * Calculates minimum length for one entry/block
242          *
243          * @return      $length         Minimum length for one entry/block
244          */
245         public function calculateMinimumBlockLength () {
246                 // Is it "cached"?
247                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
248                 if (self::$minimumBlockLength == 0) {
249                         // Calulcate it
250                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calculating ...');
251                         self::$minimumBlockLength = (
252                                 // Type
253                                 BinaryFile::LENGTH_TYPE + strlen(chr(BinaryFile::SEPARATOR_TYPE_POSITION)) +
254                                 // Position
255                                 BinaryFile::LENGTH_POSITION + strlen(chr(BinaryFile::SEPARATOR_ENTRIES))
256                         );
257                 }
258
259                 // Return it
260                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: self::minimumBlockLength=%d - EXIT!', self::$minimumBlockLength));
261                 return self::$minimumBlockLength;
262         }
263
264         /**
265          * "Getter" for file size
266          *
267          * @return      $fileSize       Size of currently loaded file
268          */
269         public function getFileSize () {
270                 // Call iterator's method
271                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
272                 $fileSize = $this->getIteratorInstance()->getBinaryFileInstance()->getFileSize();
273
274                 // Return it
275                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: fileSize=%d - EXIT!', $fileSize));
276                 return $fileSize;
277         }
278
279         /**
280          * Searches for next suitable gap the given length of data can fit in
281          * including padding bytes.
282          *
283          * @param       $length                 Length of raw data
284          * @return      $seekPosition   Found next gap's seek position
285          * @throws      InvalidArgumentException        If the parameter is not valid
286          * @todo        Unfinished work
287          */
288         public function searchNextGap (int $length) {
289                 // Validate parameter
290                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: length=%d - CALLED!', $length));
291                 if ($length <= 0) {
292                         // Throw IAE
293                         throw new InvalidArgumentException(sprintf('length=%d is not valid', $length));
294                 }
295
296                 // Debug message
297                 /* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: length=%d,this=%s', __METHOD__, __LINE__, $length, print_r($this, true)));
298         }
299
300         /**
301          * Writes at given position by seeking to it.
302          *
303          * @param       $seekPosition   Seek position in file
304          * @param       $dataStream             Data to be written
305          * @return      mixed                   Number of writes bytes or false on error
306          * @throws      OutOfBoundsException    If the position is not seekable
307          * @throws      InvalidArgumentException        If a parameter is not valid
308          */
309         public function writeAtPosition (int $seekPosition, string $dataStream) {
310                 // Validate parameter
311                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: seekPosition=%d,dataStream(%d)=%s - CALLED!', $seekPosition, strlen($dataStream), $dataStream));
312                 if ($seekPosition < 0) {
313                         // Invalid seek position
314                         throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid.', $seekPosition));
315                 } elseif (empty($dataStream)) {
316                         // Empty dataStream
317                         throw new InvalidArgumentException('Parameter "dataStream" is empty');
318                 }
319
320                 // Call iterated object's method
321                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Calling this->iteratorInstance->binaryFileInstance->writeAtPosition(%d, %s) ...', $seekPosition, $dataStream));
322                 $status = $this->getIteratorInstance()->getBinaryFileInstance()->writeAtPosition($seekPosition, $dataStream);
323
324                 // Return status
325                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: status[%s]=%d - EXIT!', gettype($status), $status));
326                 return $status;
327         }
328
329         /**
330          * Checks if this index has been fully and properly loaded.
331          *
332          * @return      $isLoaded       Whether this index has been loaded
333          */
334         public function isIndexLoaded () {
335                 // Is the file gaps-only?
336                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
337                 if ($this->getIteratorInstance()->getBinaryFileInstance()->isFileGapsOnly()) {
338                         // Then skip below code as this implies the file has been fully analyzed and "loaded"
339                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Underlaying file is gaps-only: Returning TRUE ... - EXIT!');
340                         return TRUE;
341                 }
342
343                 // Debug message
344                 /* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this=%s', __METHOD__, __LINE__, print_r($this, true)));
345         }
346
347 }