]> git.mxchange.org Git - core.git/blob - framework/main/classes/utils/string/class_StringUtils.php
b114566a8a58b4db2f66bce7b67f449bdfd689f9
[core.git] / framework / main / classes / utils / string / class_StringUtils.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Utils\String;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Configuration\FrameworkConfiguration;
8 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
9 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
10
11 // Import SPL stuff
12 use \InvalidArgumentException;
13
14 /**
15  * A string utility class
16  *
17  * @author              Roland Haeder <webmaster@ship-simu.org>
18  * @version             0.0.0
19  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
20  * @license             GNU GPL 3.0 or any newer version
21  * @link                http://www.ship-simu.org
22  *
23  * This program is free software: you can redistribute it and/or modify
24  * it under the terms of the GNU General Public License as published by
25  * the Free Software Foundation, either version 3 of the License, or
26  * (at your option) any later version.
27  *
28  * This program is distributed in the hope that it will be useful,
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
31  * GNU General Public License for more details.
32  *
33  * You should have received a copy of the GNU General Public License
34  * along with this program. If not, see <http://www.gnu.org/licenses/>.
35  */
36 final class StringUtils extends BaseFrameworkSystem {
37         /**
38          * Thousands separator
39          */
40         private static $thousands = ''; // German
41
42         /**
43          * Decimal separator
44          */
45         private static $decimals  = ''; // German
46
47         /**
48          * Array with bitmasks and such for pack/unpack methods to support both
49          * 32-bit and 64-bit systems
50          */
51         private static $packingData = [
52                 32 => [
53                         'step'   => 3,
54                         'left'   => 0xffff0000,
55                         'right'  => 0x0000ffff,
56                         'factor' => 16,
57                         'format' => 'II',
58                 ],
59                 64 => [
60                         'step'   => 7,
61                         'left'   => 0xffffffff00000000,
62                         'right'  => 0x00000000ffffffff,
63                         'factor' => 32,
64                         'format' => 'NN'
65                 ]
66         ];
67
68         /**
69          * Hexadecimal->Decimal translation array
70          */
71         private static $hexdec = [
72                 '0' => 0,
73                 '1' => 1,
74                 '2' => 2,
75                 '3' => 3,
76                 '4' => 4,
77                 '5' => 5,
78                 '6' => 6,
79                 '7' => 7,
80                 '8' => 8,
81                 '9' => 9,
82                 'a' => 10,
83                 'b' => 11,
84                 'c' => 12,
85                 'd' => 13,
86                 'e' => 14,
87                 'f' => 15
88         ];
89
90         /**
91          * Decimal->hexadecimal translation array
92          */
93         private static $dechex = [
94                  0 => '0',
95                  1 => '1',
96                  2 => '2',
97                  3 => '3',
98                  4 => '4',
99                  5 => '5',
100                  6 => '6',
101                  7 => '7',
102                  8 => '8',
103                  9 => '9',
104                 10 => 'a',
105                 11 => 'b',
106                 12 => 'c',
107                 13 => 'd',
108                 14 => 'e',
109                 15 => 'f'
110         ];
111
112         /**
113          * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
114          *
115          * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
116          */
117         private static $archArrayElement = 0;
118
119         /**
120          * Private constructor, no instance needed. If PHP would have a static initializer ...
121          *
122          * @return      void
123          */
124         private function __construct () {
125                 // Call parent constructor
126                 parent::__construct(__CLASS__);
127
128                 // Is one not set?
129                 if (empty(self::$archArrayElement)) {
130                         // Set array element
131                         self::$archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
132
133                         // Init from configuration
134                         self::$thousands = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('thousands_separator');
135                         self::$decimals = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('decimals_separator');
136                 }
137         }
138
139         /**
140          * Converts dashes to underscores, e.g. useable for configuration entries
141          *
142          * @param       $str    The string with maybe dashes inside
143          * @return      $str    The converted string with no dashed, but underscores
144          * @throws      NullPointerException    If $str is null
145          * @throws      InvalidArgumentException        If $str is empty
146          */
147         public static function convertDashesToUnderscores (string $str) {
148                 // Validate parameter
149                 if (empty($str)) {
150                         // Entry is empty
151                         throw new InvalidArgumentException('Parameter "str" is empty');
152                 }
153
154                 // Convert them all
155                 $str = str_replace('-', '_', $str);
156
157                 // Return converted string
158                 return $str;
159         }
160
161         /**
162          * Encodes raw data (almost any type) by "serializing" it and then pack it
163          * into a "binary format".
164          *
165          * @param       $rawData        Raw data (almost any type)
166          * @return      $encoded        Encoded data
167          * @throws      InvalidArgumentException        If $rawData has a non-serializable data type
168          */
169         public static function encodeData ($rawData) {
170                 // Make sure no objects or resources pass through
171                 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: rawData[]=%s - CALLED!', gettype($rawData)));
172                 if (is_object($rawData) || is_resource($rawData)) {
173                         // Not all variable types should be serialized here
174                         throw new InvalidArgumentException(sprintf('rawData[]=%s cannot be serialized.', gettype($rawData)));
175                 }
176
177                 // Init instance
178                 $dummyInstance = new StringUtils();
179
180                 // First "serialize" it (json_encode() is faster than serialize())
181                 $encoded = self::packString(json_encode($rawData));
182
183                 // And return it
184                 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: encoded()=%d - EXIT!', strlen($encoded)));
185                 return $encoded;
186         }
187
188         /**
189          * Converts e.g. a command from URL to a valid class by keeping out bad characters
190          *
191          * @param       $str            The string, what ever it is needs to be converted
192          * @return      $className      Generated class name
193          */
194         public static final function convertToClassName (string $str) {
195                 // Init class name
196                 $className = '';
197
198                 // Convert all dashes in underscores
199                 $str = self::convertDashesToUnderscores($str);
200
201                 // Now use that underscores to get classname parts for hungarian style
202                 foreach (explode('_', $str) as $strPart) {
203                         // Make the class name part lower case and first upper case
204                         $className .= ucfirst(strtolower($strPart));
205                 }
206
207                 // Return class name
208                 return $className;
209         }
210
211         /**
212          * Formats computer generated price values into human-understandable formats
213          * with thousand and decimal separators.
214          *
215          * @param       $value          The in computer format value for a price
216          * @param       $currency       The currency symbol (use HTML-valid characters!)
217          * @param       $decNum         Number of decimals after commata
218          * @return      $price          The for the current language formated price string
219          * @throws      MissingDecimalsThousandsSeparatorException      If decimals or thousands separator is missing
220          */
221         public static function formatCurrency (float $value, string $currency = '&euro;', int $decNum = 2) {
222                 // Init instance
223                 $dummyInstance = new StringUtils();
224
225                 // Reformat the US number
226                 $price = number_format($value, $decNum, self::$decimals, self::$thousands) . $currency;
227
228                 // Return as string...
229                 return $price;
230         }
231
232         /**
233          * Converts a hexadecimal string, even with negative sign as first string to
234          * a decimal number using BC functions.
235          *
236          * This work is based on comment #86673 on php.net documentation page at:
237          * <http://de.php.net/manual/en/function.dechex.php#86673>
238          *
239          * @param       $hex    Hexadecimal string
240          * @return      $dec    Decimal number
241          */
242         public static function hex2dec (string $hex) {
243                 // Convert to all lower-case
244                 $hex = strtolower($hex);
245
246                 // Detect sign (negative/positive numbers)
247                 $sign = '';
248                 if (substr($hex, 0, 1) == '-') {
249                         $sign = '-';
250                         $hex = substr($hex, 1);
251                 }
252
253                 // Decode the hexadecimal string into a decimal number
254                 $dec = 0;
255                 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
256                         $factor = self::$hexdec[substr($hex, $i, 1)];
257                         $dec = bcadd($dec, bcmul($factor, $e));
258                 }
259
260                 // Return the decimal number
261                 return $sign . $dec;
262         }
263
264         /**
265          * Converts even very large decimal numbers, also signed, to a hexadecimal
266          * string.
267          *
268          * This work is based on comment #97756 on php.net documentation page at:
269          * <http://de.php.net/manual/en/function.hexdec.php#97756>
270          *
271          * @param       $dec            Decimal number, even with negative sign
272          * @param       $maxLength      Optional maximum length of the string
273          * @return      $hex    Hexadecimal string
274          */
275         public static function dec2hex (string $dec, int $maxLength = 0) {
276                 // maxLength can be zero or devideable by 2
277                 assert(($maxLength == 0) || (($maxLength % 2) == 0));
278
279                 // Detect sign (negative/positive numbers)
280                 $sign = '';
281                 if ($dec < 0) {
282                         $sign = '-';
283                         $dec = abs($dec);
284                 }
285
286                 // Encode the decimal number into a hexadecimal string
287                 $hex = '';
288                 do {
289                         $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
290                         $dec /= (2 ^ 4);
291                 } while ($dec >= 1);
292
293                 /*
294                  * Leading zeros are required for hex-decimal "numbers". In some
295                  * situations more leading zeros are wanted, so check for both
296                  * conditions.
297                  */
298                 if ($maxLength > 0) {
299                         // Prepend more zeros
300                         $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
301                 } elseif ((strlen($hex) % 2) != 0) {
302                         // Only make string's length dividable by 2
303                         $hex = '0' . $hex;
304                 }
305
306                 // Return the hexadecimal string
307                 return $sign . $hex;
308         }
309
310         /**
311          * Converts a ASCII string (0 to 255) into a decimal number.
312          *
313          * @param       $asc    The ASCII string to be converted
314          * @return      $dec    Decimal number
315          */
316         public static function asc2dec (string $asc) {
317                 // Convert it into a hexadecimal number
318                 $hex = bin2hex($asc);
319
320                 // And back into a decimal number
321                 $dec = self::hex2dec($hex);
322
323                 // Return it
324                 return $dec;
325         }
326
327         /**
328          * Converts a decimal number into an ASCII string.
329          *
330          * @param       $dec            Decimal number
331          * @return      $asc    An ASCII string
332          */
333         public static function dec2asc (string $dec) {
334                 // First convert the number into a hexadecimal string
335                 $hex = self::dec2hex($dec);
336
337                 // Then convert it into the ASCII string
338                 $asc = self::hex2asc($hex);
339
340                 // Return it
341                 return $asc;
342         }
343
344         /**
345          * Converts a hexadecimal number into an ASCII string. Negative numbers
346          * are not allowed.
347          *
348          * @param       $hex    Hexadecimal string
349          * @return      $asc    An ASCII string
350          */
351         public static function hex2asc ($hex) {
352                 // Check for length, it must be devideable by 2
353                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
354                 assert((strlen($hex) % 2) == 0);
355
356                 // Walk the string
357                 $asc = '';
358                 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
359                         // Get the decimal number of the chunk
360                         $part = hexdec(substr($hex, $idx, 2));
361
362                         // Add it to the final string
363                         $asc .= chr($part);
364                 }
365
366                 // Return the final string
367                 return $asc;
368         }
369
370         /**
371          * Pack a string into a "binary format". Please execuse me that this is
372          * widely undocumented. :-(
373          *
374          * @param       $str            Unpacked string
375          * @return      $packed         Packed string
376          * @todo        Improve documentation
377          */
378         private static function packString (string $str) {
379                 // First compress the string (gzcompress is okay)
380                 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: str=%s - CALLED!', $str));
381                 $str = gzcompress($str);
382
383                 // Init variable
384                 $packed = '';
385
386                 // And start the "encoding" loop
387                 for ($idx = 0; $idx < strlen($str); $idx += self::$packingData[self::$archArrayElement]['step']) {
388                         $big = 0;
389                         for ($i = 0; $i < self::$packingData[self::$archArrayElement]['step']; $i++) {
390                                 $factor = (self::$packingData[self::$archArrayElement]['step'] - 1 - $i);
391
392                                 if (($idx + $i) <= strlen($str)) {
393                                         $ord = ord(substr($str, ($idx + $i), 1));
394
395                                         $add = $ord * pow(256, $factor);
396
397                                         $big += $add;
398
399                                         //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
400                                 }
401                         }
402
403                         // Left/right parts (low/high?)
404                         $l = ($big & self::$packingData[self::$archArrayElement]['left']) >>self::$packingData[self::$archArrayElement]['factor'];
405                         $r = $big & self::$packingData[self::$archArrayElement]['right'];
406
407                         // Create chunk
408                         $chunk = str_pad(pack(self::$packingData[self::$archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
409                         //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: big=%d,chunk(%d)=%s', $big, strlen($chunk), md5($chunk)));
410
411                         $packed .= $chunk;
412                 } // END - for
413
414                 // Return it
415                 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: packed=%s - EXIT!', $packed));
416                 return $packed;
417         }
418
419         /**
420          * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
421          *
422          * @param       $num    A string consisting only chars between 0 and 9
423          * @param       $assertMismatch         Whether to assert mismatches
424          * @return      $ret    The (hopefully) secured hext-numbered value
425          */
426         public static function hexval (string $num, bool $assertMismatch = false) {
427                 // Filter all numbers out
428                 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
429
430                 // Assert only if requested
431                 if ($assertMismatch === true) {
432                         // Has the whole value changed?
433                         assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
434                 }
435
436                 // Return result
437                 return $ret;
438         }
439
440 }