]> git.mxchange.org Git - core.git/blob - framework/main/classes/index/class_BaseIndex.php
Continued:
[core.git] / framework / main / classes / index / class_BaseIndex.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Index;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
7 use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
8 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
9 use Org\Mxchange\CoreFramework\Iterator\Filesystem\SeekableWritableFileIterator;
10 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
11 use Org\Mxchange\CoreFramework\Utils\String\StringUtils;
12 use Org\Mxchange\CoreFramework\Traits\Iterator\IteratorTrait;
13
14 // Import SPL stuff
15 use \SplFileInfo;
16 use \UnexpectedValueException;
17
18 /**
19  * A general index class
20  *
21  * @author              Roland Haeder <webmaster@ship-simu.org>
22  * @version             0.0.0
23  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
24  * @license             GNU GPL 3.0 or any newer version
25  * @link                http://www.ship-simu.org
26  *
27  * This program is free software: you can redistribute it and/or modify
28  * it under the terms of the GNU General Public License as published by
29  * the Free Software Foundation, either version 3 of the License, or
30  * (at your option) any later version.
31  *
32  * This program is distributed in the hope that it will be useful,
33  * but WITHOUT ANY WARRANTY; without even the implied warranty of
34  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
35  * GNU General Public License for more details.
36  *
37  * You should have received a copy of the GNU General Public License
38  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
39  */
40 abstract class BaseIndex extends BaseFrameworkSystem {
41         // Load traits
42         use IteratorTrait;
43
44         /**
45          * Magic for this index
46          */
47         const INDEX_MAGIC = 'INDEXv0.1';
48
49         /**
50          * Separator group->hash
51          */
52         const SEPARATOR_GROUP_HASH = 0x01;
53
54         /**
55          * Separator hash->gap position
56          */
57         const SEPARATOR_HASH_GAP_POSITION = 0x02;
58
59         /**
60          * Separator gap position->length
61          */
62         const SEPARATOR_GAP_LENGTH = 0x03;
63
64         /**
65          * Minimum block length
66          */
67         private static $minimumBlockLength = 0;
68
69         /**
70          * Protected constructor
71          *
72          * @param       $className      Name of the class
73          * @return      void
74          */
75         protected function __construct (string $className) {
76                 // Call parent constructor
77                 parent::__construct($className);
78         }
79
80         /**
81          * Reads the file header
82          *
83          * @return      void
84          * @throws      UnexpectedValueException        If header length or count of elements is invalid
85          */
86         public function readFileHeader () {
87                 // First rewind to beginning as the header sits at the beginning ...
88                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-INDEX: CALLED!');
89                 $this->getIteratorInstance()->rewind();
90
91                 // Then read it (see constructor for calculation)
92                 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
93
94                 // Have all requested bytes been read?
95                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-INDEX: Read %d bytes (%d wanted).', strlen($data), $this->getIteratorInstance()->getHeaderSize()));
96                 if (strlen($data) != $this->getIteratorInstance()->getHeaderSize()) {
97                         // Invalid header length
98                         throw new UnexpectedValueException(sprintf('data(%d)=%s is not expected length %d',
99                                 strlen($data),
100                                 $data,
101                                 $this->getIteratorInstance()->getHeaderSize()
102                         ));
103                 } elseif (substr($data, -1, 1) != chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)) {
104                         // Bad last character
105                         throw new UnexpectedValueException(sprintf('data=%s does not end with "%s"',
106                                 $data,
107                                 chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
108                         ));
109                 }
110
111                 // Okay, then remove it
112                 $data = substr($data, 0, -1);
113
114                 // And update seek position
115                 $this->getIteratorInstance()->updateSeekPosition();
116
117                 /*
118                  * Now split it:
119                  *
120                  * 0 => magic
121                  * 1 => total entries
122                  */
123                 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
124
125                 // Check if the array has only 3 elements
126                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-INDEX: header()=%d', count($header)));
127                 //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-INDEX: header(%d)=%s', count($header), print_r($header, true)));
128                 if (count($header) != 2) {
129                         // Bad header
130                         throw new UnexpectedValueException(sprintf('header()=%d is not expected value 2', count($header)));
131                 } elseif ($header[0] !== self::INDEX_MAGIC) {
132                         // Magic must be in first element
133                         throw new UnexpectedValueException(sprintf('header[0]=%s is not the expected magic (%s)', $header[0], self::INDEX_MAGIC));
134                 } elseif (strlen($header[1]) != BaseBinaryFile::LENGTH_COUNT) {
135                         // Length of total entries not matching
136                         throw new UnexpectedValueException(sprintf('header[1](%d)=%s does not have expected length %d', strlen($header[1]), $header[1], BaseBinaryFile::LENGTH_COUNT));
137                 }
138
139                 // Decode count
140                 $header[1] = hex2bin($header[1]);
141
142                 // Set it here
143                 $this->getIteratorInstance()->setHeader($header);
144
145                 // Trace message
146                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-INDEX: EXIT!');
147         }
148
149         /**
150          * Flushes the file header
151          *
152          * @return      void
153          */
154         public function flushFileHeader () {
155                 // Put all informations together
156                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-INDEX: CALLED!');
157                 $header = sprintf('%s%s%s%s',
158                         // Magic
159                         self::INDEX_MAGIC,
160
161                         // Separator header data
162                         chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
163
164                         // Total entries
165                         str_pad(StringUtils::dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
166
167                         // Separator header<->entries
168                         chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
169                 );
170
171                 // Write it to disk (header is always at seek position 0)
172                 $this->getIteratorInstance()->writeData(0, $header, false);
173
174                 // Trace message
175                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-INDEX: EXIT!');
176         }
177
178         /**
179          * Initializes this index
180          *
181          * @param       $fileInfoInstance       An instance of a SplFileInfo class
182          * @return      void
183          * @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.
184          */
185         protected function initIndex (SplFileInfo $fileInfoInstance) {
186                 // Get a file i/o pointer instance for index file
187                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-INDEX: fileInfoInstance[%s]=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance));
188                 $fileInstance = ObjectFactory::createObjectByConfiguredName('index_file_class', array($fileInfoInstance, $this));
189
190                 // Get iterator instance
191                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
192
193                 // Set iterator here
194                 $this->setIteratorInstance($iteratorInstance);
195
196                 // Calculate header size
197                 $this->getIteratorInstance()->setHeaderSize(
198                         strlen(self::INDEX_MAGIC) +
199                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
200                         BaseBinaryFile::LENGTH_COUNT +
201                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
202                 );
203
204                 // Init counters and gaps array
205                 $this->getIteratorInstance()->initCountersGapsArray();
206
207                 // Is the file's header initialized?
208                 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
209                         // No, then create it (which may pre-allocate the index)
210                         $this->getIteratorInstance()->createFileHeader();
211
212                         // And pre-allocate a bit
213                         $this->getIteratorInstance()->preAllocateFile('index');
214                 }
215
216                 // Load the file header
217                 $this->readFileHeader();
218
219                 // Count all entries in file
220                 $this->getIteratorInstance()->analyzeFile();
221
222                 // Trace message
223                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-INDEX: EXIT!');
224         }
225
226         /**
227          * Calculates minimum length for one entry/block
228          *
229          * @return      $length         Minimum length for one entry/block
230          */
231         public function calculateMinimumBlockLength () {
232                 // Is it "cached"?
233                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-INDEX: CALLED!');
234                 if (self::$minimumBlockLength == 0) {
235                         // Calulcate it
236                         self::$minimumBlockLength = (
237                                 // Type
238                                 BaseBinaryFile::LENGTH_TYPE + strlen(chr(BaseBinaryFile::SEPARATOR_TYPE_POSITION)) +
239                                 // Position
240                                 BaseBinaryFile::LENGTH_POSITION + strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES))
241                         );
242                 }
243
244                 // Return it
245                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-INDEX: self::minimumBlockLength=%d - EXIT!', self::$minimumBlockLength));
246                 return self::$minimumBlockLength;
247         }
248
249         /**
250          * Determines whether the EOF has been reached
251          *
252          * @return      $isEndOfFileReached             Whether the EOF has been reached
253          * @throws      UnsupportedOperationException   If this method is called
254          */
255         public function isEndOfFileReached () {
256                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
257         }
258
259         /**
260          * Initializes counter for valid entries, arrays for damaged entries and
261          * an array for gap seek positions. If you call this method on your own,
262          * please re-analyze the file structure. So you are better to call
263          * analyzeFile() instead of this method.
264          *
265          * @return      void
266          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
267          */
268         public function initCountersGapsArray () {
269                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
270         }
271
272         /**
273          * Getter for header size
274          *
275          * @return      $totalEntries   Size of file header
276          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
277          */
278         public final function getHeaderSize () {
279                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
280         }
281
282         /**
283          * Setter for header size
284          *
285          * @param       $headerSize             Size of file header
286          * @return      void
287          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
288          */
289         public final function setHeaderSize (int $headerSize) {
290                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
291         }
292
293         /**
294          * Getter for header array
295          *
296          * @return      $totalEntries   Size of file header
297          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
298          */
299         public final function getHeader () {
300                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
301         }
302
303         /**
304          * Setter for header
305          *
306          * @param       $header         Array for a file header
307          * @return      void
308          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
309          */
310         public final function setHeader (array $header) {
311                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
312         }
313
314         /**
315          * Updates seekPosition attribute from file to avoid to much access on file.
316          *
317          * @return      void
318          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
319          */
320         public function updateSeekPosition () {
321                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
322         }
323
324         /**
325          * Getter for total entries
326          *
327          * @return      $totalEntries   Total entries in this file
328          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
329          */
330         public final function getCounter () {
331                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
332         }
333
334         /**
335          * "Getter" for file size
336          *
337          * @return      $fileSize       Size of currently loaded file
338          */
339         public function getFileSize () {
340                 // Call iterator's method
341                 return $this->getIteratorInstance()->getFileSize();
342         }
343
344         /**
345          * Writes data at given position
346          *
347          * @param       $seekPosition   Seek position
348          * @param       $data                   Data to be written
349          * @param       $flushHeader    Whether to flush the header (default: flush)
350          * @return      void
351          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
352          */
353         public function writeData (int $seekPosition, string $data, bool $flushHeader = true) {
354                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('seekPosition=%s,data[]=%s,flushHeader=%d - CALLED!', $seekPosition, gettype($data), intval($flushHeader)));
355                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
356         }
357
358         /**
359          * Writes given value to the file and returns a hash and gap position for it
360          *
361          * @param       $groupId        Group identifier
362          * @param       $value          Value to be added to the stack
363          * @return      $data           Hash and gap position
364          * @throws      UnsupportedOperationException   If this method is called
365          */
366         public function writeValueToFile (string $groupId, $value) {
367                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('groupId=%s,value[%s]=%s - CALLED!', $groupId, gettype($value), print_r($value, true)));
368                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
369         }
370
371         /**
372          * Writes given raw data to the file and returns a gap position and length
373          *
374          * @param       $groupId        Group identifier
375          * @param       $hash           Hash from encoded value
376          * @param       $encoded        Encoded value to be written to the file
377          * @return      $data           Gap position and length of the raw data
378          */
379         public function writeDataToFreeGap (string $groupId, string $hash, string $encoded) {
380                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('groupId=%s,hash=%s,encoded()=%d - CALLED!', $groupId, $hash, strlen($encoded)));
381                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
382         }
383
384 }