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