]> git.mxchange.org Git - core.git/blob - framework/main/classes/file_directories/binary/index/class_IndexFile.php
Continued:
[core.git] / framework / main / classes / file_directories / binary / index / class_IndexFile.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Filesystem\Index;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
8 use Org\Mxchange\CoreFramework\Filesystem\Index\IndexableFile;
9 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
10 use Org\Mxchange\CoreFramework\Index\Indexable;
11 use Org\Mxchange\CoreFramework\Utils\Crypto\CryptoUtils;
12
13 // Import SPL stuff
14 use \BadMethodCallException;
15 use \InvalidArgumentException;
16 use \SplFileInfo;
17
18 /**
19  * An index file class
20  *
21  * @author              Roland Haeder <webmaster@ship-simu.org>
22  * @version             0.0.0
23  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2022 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 class IndexFile extends BaseBinaryFile implements IndexableFile {
41         /**
42          * Protected constructor
43          *
44          * @return      void
45          */
46         private function __construct () {
47                 // Call parent constructor
48                 parent::__construct(__CLASS__);
49         }
50
51         /**
52          * Creates an instance of this File class and prepares it for usage
53          *
54          * @param       $fileInfoInstance       An instance of a SplFileInfo class
55          * @param       $indexInstance  An instance of a Indexable class
56          * @return      $indexFileInstance      An instance of an IndexableFile class
57          */
58         public final static function createIndexFile (SplFileInfo $fileInfoInstance, Indexable $indexInstance) {
59                 // Get a new instance
60                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('INDEX-FILE: fileInfoInstance[%s]=%s,indexInstance=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance, $indexInstance->__toString()));
61                 $indexFileInstance = new IndexFile();
62
63                 // Set file instance here for callbacks
64                 $indexFileInstance->setIndexInstance($indexInstance);
65
66                 // Expand file name with .idx
67                 $indexInfoInstance = new SplFileInfo(sprintf('%s.idx', $fileInfoInstance->__toString()));
68
69                 // Init this abstract file
70                 $indexFileInstance->initFile($indexInfoInstance);
71
72                 // Init counters and gaps array
73                 $indexFileInstance->initCountersGapsArray();
74
75                 // Return the prepared instance
76                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('INDEX-FILE: indexFileInstance=%s - EXIT!', $indexFileInstance->__toString()));
77                 return $indexFileInstance;
78         }
79
80         /**
81          * Flushes the file header
82          *
83          * @return      void
84          * @throws      BadMethodCallException  If this->indexInstance is not properly set
85          */
86         public function flushFileHeader () {
87                 // Validate call
88                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('INDEX-FILE: CALLED!');
89                 if (!($this->getIndexInstance() instanceof Indexable)) {
90                         // Index instance not set
91                         throw new BadMethodCallException('this->indexInstance[] is not properly set.');
92                 }
93
94                 // Call block instance
95                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('INDEX-FILE: Calling this->indexInstance->flushFileHeader() ...');
96                 $this->getIndexInstance()->flushFileHeader();
97
98                 // Trace message
99                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('INDEX-FILE: EXIT!');
100         }
101
102         /**
103          * Pre-allocates file (if enabled) with some space for later faster write access.
104          *
105          * @param       $type   Type of the file
106          * @return      void
107          * @throws      InvalidArgumentException        If a parameter is empty
108          * @throws      BadMethodCallException  If this->indexInstance is not properly set
109          */
110         public function preAllocateFile (string $type) {
111                 // Is it enabled?
112                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('INDEX-FILE: type=%s - CALLED!', $type));
113                 if (empty($type)) {
114                         // Empty type
115                         throw new InvalidArgumentException('Parameter "type" is empty');
116                 } elseif (!($this->getIndexInstance() instanceof Indexable)) {
117                         // Index instance not set
118                         throw new BadMethodCallException('this->indexInstance[] is not properly set.');
119                 }
120
121                 // Message to user
122                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('INDEX-FILE: Pre-allocating file ...');
123
124                 // Calculate minimum block length
125                 $minimumBlockLength = $this->getIndexInstance()->calculateMinimumBlockLength();
126
127                 // Call protected method
128                 $this->preAllocateFileByTypeLength($type, $minimumBlockLength);
129
130                 // Trace message
131                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('INDEX-FILE: EXIT!');
132         }
133
134         /**
135          * Checks wether the current entry is valid (not at the end of the file).
136          * This method will return true if an emptied (nulled) entry has been found.
137          *
138          * @return      $isValid        Whether the next entry is valid
139          * @throws      UnexpectedValueException        If some value is not expected
140          * @throws      BadMethodCallException  If this->indexInstance is not properly set
141          */
142         public function isValid () {
143                 // Validate call
144                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('INDEX-FILE: CALLED!');
145                 if (!($this->getIndexInstance() instanceof Indexable)) {
146                         // Index instance not set
147                         throw new BadMethodCallException('this->indexInstance[] is not properly set.');
148                 }
149
150                 // Get length from index
151                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('INDEX-FILE: Calling this->indexInstance->calculateMinimumBlockLength() ...');
152                 $length = $this->getIndexInstance()->calculateMinimumBlockLength();
153
154                 // Call protected method
155                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('INDEX-FILE: Calling this->isValidByLength(%d) ...', $length));
156                 $isValid = $this->isValidByLength($length);
157
158                 // Return result
159                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('INDEX-FILE: isValid=%d - EXIT!', intval($isValid)));
160                 return $isValid;
161         }
162
163         /**
164          * Reads next "block" of bytes into $currentBlock field. THis method loads
165          * the whole file into memory when the file is just freshly initialized
166          * (only zeros in it).
167          *
168          * @return      void
169          */
170         protected function readNextBlock () {
171                 // First calculate minimum block length
172                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('INDEX-FILE: this->seekPosition=%d - CALLED!', $this->getSeekPosition()));
173                 $length = $this->getIndexInstance()->calculateMinimumBlockLength();
174
175                 // Call protected method
176                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('INDEX-FILE: Calling parent::readNextBlockByLength(%d) ...', $length));
177                 parent::readNextBlockByLength($length);
178
179                 // Trace message
180                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('INDEX-FILE: EXIT!');
181         }
182
183         /**
184          * Reads the file header
185          *
186          * @return      void
187          */
188         public function readFileHeader () {
189                 // Call index class' method
190                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('INDEX-FILE: Calling this->indexInstance->readIndexHeader() - CALLED!');
191                 $this->getIndexInstance()->readIndexHeader();
192
193                 // Trace message
194                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('INDEX-FILE: EXIT!');
195         }
196
197         /**
198          * Writes given value to the file and returns a hash and gap position for it
199          *
200          * @param       $stackName      Group identifier
201          * @param       $value          Value to be added to the stack
202          * @return      $data           Hash and gap position
203          * @throws      InvalidArgumentException        If a parameter is not valid
204          * @throws      BadMethodCallException  If this->indexInstance is not properly set
205          */
206         public function writeValueToFile (string $stackName, $value) {
207                 // Validate parameter
208                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('INDEX-FILE: stackName=%s,value[]=%s - CALLED!', $stackName, gettype($value)));
209                 if (empty($stackName)) {
210                         // Throw IAE
211                         throw new InvalidArgumentException('Parameter "stackName" is empty');
212                 } elseif (is_object($value) || is_resource($value)) {
213                         // Not wanted here
214                         throw new InvalidArgumentException(sprintf('value[]=%s is not stackable in files', gettype($value)));
215                 } elseif (!($this->getIndexInstance() instanceof Indexable)) {
216                         // Index instance not set
217                         throw new BadMethodCallException('this->indexInstance[] is not properly set.');
218                 }
219
220                 // Encode/convert the value into a "binary format"
221                 $encoded = StringUtils::encodeData($value);
222
223                 // Get a strong hash for the "encoded" data
224                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('INDEX-FILE: encoded=%s', $encoded));
225                 $hash = CryptoUtils::hash($encoded);
226
227                 // Then write it to the next free gap
228                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('INDEX-FILE: hash=%s', $hash));
229                 $data = $this->getIndexInstance()->writeDataToFreeGap($stackName, $hash, $encoded);
230
231                 // Return info
232                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('INDEX-FILE: data[]=%s - EXIT!', gettype($data)));
233                 return $data;
234         }
235
236         /**
237          * Writes given raw data to the file and returns a gap position and length
238          *
239          * @param       $stackName      Group identifier
240          * @param       $hash           Hash from encoded value
241          * @param       $encoded        Encoded value to be written to the file
242          * @return      $data           Gap position and length of the raw data
243          * @throws      UnsupportedOperationException   If this method is called
244          */
245         public function writeDataToFreeGap (string $stackName, string $hash, string $encoded) {
246                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('INDEX-FILE: stackName=' . $stackName . ',hash=' . $hash . ',encoded()=' . strlen($encoded));
247                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
248         }
249
250 }