Passed
Push — master ( bae7fb...bdda0d )
by Sebastian
03:37
created

ConvertHelper::createControlCharacters()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * File containing the {@see AppUtils\ConvertHelper} class.
4
 * 
5
 * @package Application Utils
6
 * @subpackage ConvertHelper
7
 * @see AppUtils\ConvertHelper
8
 */
9
10
namespace AppUtils;
11
12
use DateInterval;
13
use DateTime;
14
15
/**
16
 * Static conversion helper class: offers a number of utility methods
17
 * to convert variable types, as well as specialized methods for working
18
 * with specific types like dates.
19
 * 
20
 * @package Application Utils
21
 * @subpackage ConvertHelper
22
 * @author Sebastian Mordziol <[email protected]>
23
 */
24
class ConvertHelper
25
{
26
    const ERROR_MONTHTOSTRING_NOT_VALID_MONTH_NUMBER = 23303;
27
    const ERROR_CANNOT_NORMALIZE_NON_SCALAR_VALUE = 23304;
28
    const ERROR_JSON_ENCODE_FAILED = 23305;
29
    const ERROR_INVALID_BOOLEAN_STRING = 23306;
30
31
    const INTERVAL_DAYS = 'days';
32
    const INTERVAL_HOURS = 'hours';
33
    const INTERVAL_MINUTES = 'minutes';
34
    const INTERVAL_SECONDS = 'seconds';
35
36
    /**
37
     * Normalizes tabs in the specified string by indenting everything
38
     * back to the minimum tab distance. With the second parameter,
39
     * tabs can optionally be converted to spaces as well (recommended
40
     * for HTML output).
41
     *
42
     * @param string $string
43
     * @param boolean $tabs2spaces
44
     * @return string
45
     */
46
    public static function normalizeTabs(string $string, bool $tabs2spaces = false) : string
47
    {
48
        return ConvertHelper_String::normalizeTabs($string, $tabs2spaces);
49
    }
50
51
    /**
52
     * Converts tabs to spaces in the specified string.
53
     * 
54
     * @param string $string
55
     * @param int $tabSize The amount of spaces per tab.
56
     * @return string
57
     */
58
    public static function tabs2spaces(string $string, int $tabSize=4) : string
59
    {
60
        return ConvertHelper_String::tabs2spaces($string, $tabSize);
61
    }
62
    
63
   /**
64
    * Converts spaces to tabs in the specified string.
65
    * 
66
    * @param string $string
67
    * @param int $tabSize The amount of spaces per tab in the source string.
68
    * @return string
69
    */
70
    public static function spaces2tabs(string $string, int $tabSize=4) : string
71
    {
72
        return ConvertHelper_String::spaces2tabs($string, $tabSize);
73
    }
74
75
    /**
76
     * Makes all hidden characters visible in the target string,
77
     * from spaces to control characters.
78
     *
79
     * @param string $string
80
     * @return string
81
     */
82
    public static function hidden2visible(string $string) : string
83
    {
84
        return ConvertHelper_String::hidden2visible($string);
85
    }
86
    
87
   /**
88
    * Converts the specified amount of seconds into
89
    * a human-readable string split in months, weeks,
90
    * days, hours, minutes and seconds.
91
    *
92
    * @param float $seconds
93
    * @return string
94
    */
95
    public static function time2string($seconds) : string
96
    {
97
        $converter = new ConvertHelper_TimeConverter($seconds);
98
        return $converter->toString();
99
    }
100
101
    /**
102
     * Converts a timestamp into an easily understandable
103
     * format, e.g. "2 hours", "1 day", "3 months"
104
     *
105
     * If you set the date to parameter, the difference
106
     * will be calculated between the two dates and not
107
     * the current time.
108
     *
109
     * @param integer|DateTime $datefrom
110
     * @param integer|DateTime $dateto
111
     * @return string
112
     *
113
     * @throws ConvertHelper_Exception
114
     * @see ConvertHelper_DurationConverter::ERROR_NO_DATE_FROM_SET
115
     */
116
    public static function duration2string($datefrom, $dateto = -1) : string
117
    {
118
         return ConvertHelper_DurationConverter::toString($datefrom, $dateto);
119
    }
120
121
   /**
122
    * Adds HTML syntax highlighting to the specified SQL string.
123
    * 
124
    * @param string $sql
125
    * @return string
126
    * @deprecated Use the Highlighter class directly instead.
127
    * @see Highlighter::sql()
128
    */
129
    public static function highlight_sql(string $sql) : string
130
    {
131
        return Highlighter::sql($sql);
132
    }
133
134
   /**
135
    * Adds HTML syntax highlighting to the specified XML code.
136
    * 
137
    * @param string $xml The XML to highlight.
138
    * @param bool $formatSource Whether to format the source with indentation to make it readable.
139
    * @return string
140
    * @deprecated Use the Highlighter class directly instead.
141
    * @see Highlighter::xml()
142
    */
143
    public static function highlight_xml(string $xml, bool $formatSource=false) : string
144
    {
145
        return Highlighter::xml($xml, $formatSource);
146
    }
147
148
   /**
149
    * @param string $phpCode
150
    * @return string
151
    * @deprecated Use the Highlighter class directly instead.
152
    * @see Highlighter::php()
153
    */
154
    public static function highlight_php(string $phpCode) : string
155
    {
156
        return Highlighter::php($phpCode);
157
    }
158
    
159
   /**
160
    * Converts a number of bytes to a human-readable form,
161
    * e.g. xx Kb / xx Mb / xx Gb
162
    *
163
    * @param int $bytes The amount of bytes to convert.
164
    * @param int $precision The amount of decimals
165
    * @param int $base The base to calculate with: Base 10 is default (=1000 Bytes in a KB), Base 2 is mainly used for Windows memory (=1024 Bytes in a KB).
166
    * @return string
167
    * 
168
    * @see https://en.m.wikipedia.org/wiki/Megabyte#Definitions
169
    */
170
    public static function bytes2readable(int $bytes, int $precision = 1, int $base = ConvertHelper_StorageSizeEnum::BASE_10) : string
171
    {
172
        return self::parseBytes($bytes)->toString($precision, $base);
173
    }
174
    
175
   /**
176
    * Parses a number of bytes, and creates a converter instance which
177
    * allows doing common operations with it.
178
    * 
179
    * @param int $bytes
180
    * @return ConvertHelper_ByteConverter
181
    */
182
    public static function parseBytes(int $bytes) : ConvertHelper_ByteConverter
183
    {
184
        return new ConvertHelper_ByteConverter($bytes);
185
    }
186
187
   /**
188
    * Cuts a text to the specified length if it is longer than the
189
    * target length. Appends a text to signify it has been cut at 
190
    * the end of the string.
191
    * 
192
    * @param string $text
193
    * @param int $targetLength
194
    * @param string $append
195
    * @return string
196
    */
197
    public static function text_cut(string $text, int $targetLength, string $append = '...') : string
198
    {
199
        return ConvertHelper_String::cutText($text, $targetLength, $append);
200
    }
201
202
    /**
203
     * Pretty `var_dump`.
204
     *
205
     * @param mixed $var
206
     * @param bool $html
207
     * @return string
208
     */
209
    public static function var_dump($var, bool $html=true) : string
210
    {
211
        $info = parseVariable($var);
212
        
213
        if($html) {
214
            return $info->toHTML();
215
        }
216
        
217
        return $info->toString();
218
    }
219
    
220
   /**
221
    * Pretty `print_r`.
222
    * 
223
    * @param mixed $var The variable to dump.
224
    * @param bool $return Whether to return the dumped code.
225
    * @param bool $html Whether to style the dump as HTML.
226
    * @return string
227
    */
228
    public static function print_r($var, bool $return=false, bool $html=true) : string
229
    {
230
        $result = parseVariable($var)->enableType()->toString();
231
        
232
        if($html) 
233
        {
234
            $result = 
235
            '<pre style="background:#fff;color:#333;padding:16px;border:solid 1px #bbb;border-radius:4px">'.
236
                $result.
237
            '</pre>';
238
        }
239
        
240
        if(!$return) 
241
        {
242
            echo $result;
243
        }
244
        
245
        return $result;
246
    }
247
    
248
   /**
249
    * Converts a string, number or boolean value to a boolean value.
250
    *
251
    * @param mixed $string
252
    * @throws ConvertHelper_Exception
253
    * @return bool
254
    *
255
    * @see ConvertHelper::ERROR_INVALID_BOOLEAN_STRING
256
    */
257
    public static function string2bool($string) : bool
258
    {
259
        return ConvertHelper_Bool::fromString($string);
260
    }
261
262
   /**
263
    * Whether the specified string is a boolean string or boolean value.
264
    * Alias for {@link ConvertHelper::isBoolean()}.
265
    *
266
    * @param mixed $string
267
    * @return bool
268
    * @deprecated
269
    * @see ConvertHelper::isBoolean()
270
    */
271
    public static function isBooleanString($string) : bool
272
    {
273
        return self::isBoolean($string);
274
    }
275
276
    /**
277
     * Alias for the {@\AppUtils\XMLHelper::string2xml()} method.
278
     *
279
     * @param string $text
280
     * @return string
281
     * @throws XMLHelper_Exception
282
     * @deprecated Use the XMLHelper method instead.
283
     */
284
    public static function text_makeXMLCompliant(string $text) : string
285
    {
286
        return XMLHelper::string2xml($text);
287
    }
288
289
    /**
290
     * Transforms a date into a generic human-readable date, optionally with time.
291
     * If the year is the same as the current one, it is omitted.
292
     *
293
     * - 6 Jan 2012
294
     * - 12 Dec 2012 17:45
295
     * - 5 Aug
296
     *
297
     * @param DateTime $date
298
     * @param bool $includeTime
299
     * @param bool $shortMonth
300
     * @return string
301
     *
302
     * @throws ConvertHelper_Exception
303
     * @see ConvertHelper::ERROR_MONTHTOSTRING_NOT_VALID_MONTH_NUMBER
304
     */
305
    public static function date2listLabel(DateTime $date, bool $includeTime = false, bool $shortMonth = false) : string
306
    {
307
        return ConvertHelper_Date::toListLabel($date, $includeTime, $shortMonth);
308
    }
309
310
    /**
311
     * Returns a human-readable month name given the month number. Can optionally
312
     * return the shorthand version of the month. Translated into the current
313
     * application locale.
314
     *
315
     * @param int|string $monthNr
316
     * @param boolean $short
317
     * @return string
318
     *
319
     * @throws ConvertHelper_Exception
320
     * @see ConvertHelper::ERROR_MONTHTOSTRING_NOT_VALID_MONTH_NUMBER
321
     */
322
    public static function month2string($monthNr, bool $short = false) : string
323
    {
324
        return ConvertHelper_Date::month2string($monthNr, $short);
325
    }
326
327
    /**
328
     * Transliterates a string.
329
     *
330
     * @param string $string
331
     * @param string $spaceChar
332
     * @param bool $lowercase
333
     * @return string
334
     */
335
    public static function transliterate(string $string, string $spaceChar = '-', bool $lowercase = true) : string
336
    {
337
        return ConvertHelper_String::transliterate($string, $spaceChar, $lowercase);
338
    }
339
    
340
   /**
341
    * Retrieves the HEX character codes for all control
342
    * characters that the {@link stripControlCharacters()} 
343
    * method will remove.
344
    * 
345
    * @return string[]
346
    */
347
    public static function getControlCharactersAsHex() : array
348
    {
349
        return self::createControlCharacters()->getCharsAsHex();
350
    }
351
    
352
   /**
353
    * Retrieves an array of all control characters that
354
    * the {@link stripControlCharacters()} method will 
355
    * remove, as the actual UTF-8 characters.
356
    * 
357
    * @return string[]
358
    */
359
    public static function getControlCharactersAsUTF8() : array
360
    {
361
        return self::createControlCharacters()->getCharsAsUTF8();
362
    }
363
    
364
   /**
365
    * Retrieves all control characters as JSON encoded
366
    * characters, e.g. "\u200b".
367
    * 
368
    * @return string[]
369
    */
370
    public static function getControlCharactersAsJSON() : array
371
    {
372
        return self::createControlCharacters()->getCharsAsJSON();
373
    }
374
375
    /**
376
     * Removes all control characters from the specified string
377
     * that can cause problems in some cases, like creating
378
     * valid XML documents. This includes invisible non-breaking
379
     * spaces.
380
     *
381
     * @param string $string
382
     * @return string
383
     * @throws ConvertHelper_Exception
384
     */
385
    public static function stripControlCharacters(string $string) : string
386
    {
387
        return self::createControlCharacters()->stripControlCharacters($string);
388
    }
389
    
390
   /**
391
    * Creates the control characters class, used to 
392
    * work with control characters in strings.
393
    * 
394
    * @return ConvertHelper_ControlCharacters
395
    */
396
    public static function createControlCharacters() : ConvertHelper_ControlCharacters
397
    {
398
        return new ConvertHelper_ControlCharacters();
399
    }
400
401
   /**
402
    * Converts a unicode character to the PHP notation.
403
    * 
404
    * Example:
405
    * 
406
    * <pre>unicodeChar2php('"\u0000"')</pre>
407
    * 
408
    * Returns
409
    * 
410
    * <pre>\x0</pre>
411
    * 
412
    * @param string $unicodeChar
413
    * @return string
414
    */
415
    public static function unicodeChar2php(string $unicodeChar) : string 
416
    {
417
        $unicodeChar = json_decode($unicodeChar);
418
        
419
        $output = '';
420
        $split = str_split($unicodeChar);
421
        
422
        foreach($split as $octet) 
423
        {
424
            $ordInt = ord($octet);
425
            // Convert from int (base 10) to hex (base 16), for PHP \x syntax
426
            $ordHex = base_convert((string)$ordInt, 10, 16);
427
            $output .= '\x' . $ordHex;
428
        }
429
        
430
        return $output;
431
    }
432
    
433
    /**
434
     * Removes the extension from the specified filename
435
     * and returns the name without the extension.
436
     *
437
     * Examples:
438
     *
439
     * <ul>
440
     *   <li>filename.html > filename</li>
441
     *   <li>passed.test.jpg > passed.test</li>
442
     *   <li>path/to/file/document.txt > document</li>
443
     * </ul>
444
     *
445
     * @param string $filename
446
     * @return string
447
     */
448
    public static function filenameRemoveExtension(string $filename) : string
449
    {
450
        return FileHelper::removeExtension($filename);
451
    }
452
453
    /**
454
     * @param mixed $a
455
     * @param mixed $b
456
     * @return bool
457
     *
458
     * @throws ConvertHelper_Exception
459
     * @see ConvertHelper::ERROR_CANNOT_NORMALIZE_NON_SCALAR_VALUE
460
     */
461
    public static function areVariablesEqual($a, $b) : bool
462
    {
463
        return ConvertHelper_Comparator::areVariablesEqual($a, $b);
464
    }
465
466
    /**
467
     * Compares two strings to check whether they are equal.
468
     * null and empty strings are considered equal.
469
     *
470
     * @param string|NULL $a
471
     * @param string|NULL $b
472
     * @return boolean
473
     *
474
     * @throws ConvertHelper_Exception
475
     * @see ConvertHelper::ERROR_CANNOT_NORMALIZE_NON_SCALAR_VALUE
476
     */
477
    public static function areStringsEqual(?string $a, ?string $b) : bool
478
    {
479
        return ConvertHelper_Comparator::areStringsEqual($a, $b);
480
    }
481
482
    /**
483
     * Checks whether the two specified numbers are equal.
484
     * null and empty strings are considered as 0 values.
485
     *
486
     * @param number|string|NULL $a
487
     * @param number|string|NULL $b
488
     * @return boolean
489
     *
490
     * @throws ConvertHelper_Exception
491
     * @see ConvertHelper::ERROR_CANNOT_NORMALIZE_NON_SCALAR_VALUE
492
     */
493
    public static function areNumbersEqual($a, $b) : bool
494
    {
495
        return ConvertHelper_Comparator::areNumbersEqual($a, $b);
496
    }
497
498
    /**
499
     * Converts a boolean value to a string. Defaults to returning
500
     * 'true' or 'false', with the additional parameter it can also
501
     * return the 'yes' and 'no' variants.
502
     *
503
     * @param boolean|string $boolean
504
     * @param boolean $yesNo
505
     * @return string
506
     * @throws ConvertHelper_Exception
507
     * @see ConvertHelper::ERROR_INVALID_BOOLEAN_STRING
508
     */
509
    public static function bool2string($boolean, bool $yesNo = false) : string
510
    {
511
        return ConvertHelper_Bool::toString($boolean, $yesNo);
512
    }
513
514
    /**
515
     * Converts a strict boolean value to string.
516
     * Cannot throw an exception like {@see ConvertHelper::bool2string()}
517
     * does.
518
     *
519
     * @param bool $boolean
520
     * @param bool $yesNo
521
     * @return string
522
     */
523
    public static function boolStrict2string(bool $boolean, bool $yesNo = false) : string
524
    {
525
        return ConvertHelper_Bool::toStringStrict($boolean, $yesNo);
526
    }
527
528
   /**
529
    * Converts an associative array with attribute name > value pairs
530
    * to an attribute string that can be used in an HTML tag. Empty 
531
    * attribute values are ignored.
532
    * 
533
    * Example:
534
    * 
535
    * array2attributeString(array(
536
    *     'id' => 45,
537
    *     'href' => 'http://www.mistralys.com'
538
    * ));
539
    * 
540
    * Result:
541
    * 
542
    * id="45" href="http://www.mistralys.com"
543
    * 
544
    * @param array<string,mixed> $array
545
    * @return string
546
    */
547
    public static function array2attributeString(array $array) : string
548
    {
549
        return ConvertHelper_Array::toAttributeString($array);
550
    }
551
    
552
   /**
553
    * Converts a string, so it can safely be used in a javascript
554
    * statement in an HTML tag: uses single quotes around the string
555
    * and encodes all special characters as needed.
556
    * 
557
    * @param string $string
558
    * @return string
559
    * @deprecated Use the JSHelper class instead.
560
    * @see JSHelper::phpVariable2AttributeJS()
561
    */
562
    public static function string2attributeJS(string $string) : string
563
    {
564
        return JSHelper::phpVariable2AttributeJS($string);
565
    }
566
    
567
   /**
568
    * Checks if the specified string is a boolean value, which
569
    * includes string representations of boolean values, like 
570
    * <code>yes</code> or <code>no</code>, and <code>true</code>
571
    * or <code>false</code>.
572
    * 
573
    * @param mixed $value
574
    * @return boolean
575
    */
576
    public static function isBoolean($value) : bool
577
    {
578
        return ConvertHelper_Bool::isBoolean($value);
579
    }
580
    
581
   /**
582
    * Converts an associative array to an HTML style attribute value string.
583
    * 
584
    * @param array<string,mixed> $subject
585
    * @return string
586
    */
587
    public static function array2styleString(array $subject) : string
588
    {
589
        return ConvertHelper_Array::toStyleString($subject);
590
    }
591
    
592
   /**
593
    * Converts a DateTime object to a timestamp, which
594
    * is PHP 5.2 compatible.
595
    * 
596
    * @param DateTime $date
597
    * @return integer
598
    */
599
    public static function date2timestamp(DateTime $date) : int
600
    {
601
        return ConvertHelper_Date::toTimestamp($date);
602
    }
603
    
604
   /**
605
    * Converts a timestamp into a DateTime instance.
606
    * @param int $timestamp
607
    * @return DateTime
608
    */
609
    public static function timestamp2date(int $timestamp) : DateTime
610
    {
611
        return ConvertHelper_Date::fromTimestamp($timestamp);
612
    }
613
    
614
   /**
615
    * Strips an absolute path to a file within the application
616
    * to make the path relative to the application root path.
617
    * 
618
    * @param string $path
619
    * @return string
620
    * 
621
    * @see FileHelper::relativizePath()
622
    * @see FileHelper::relativizePathByDepth()
623
    */
624
    public static function fileRelativize(string $path) : string
625
    {
626
        return FileHelper::relativizePathByDepth($path);
627
    }
628
    
629
    /**
630
    * Converts a PHP regex to a javascript RegExp object statement.
631
    * 
632
    * NOTE: This is an alias for the JSHelper's `convertRegex` method. 
633
    * More details are available on its usage there.
634
    *
635
    * @param string $regex A PHP preg regex
636
    * @param string $statementType The type of statement to return: Defaults to a statement to create a RegExp object.
637
    * @return string Depending on the specified return type.
638
    * 
639
    * @see JSHelper::buildRegexStatement()
640
    */
641
    public static function regex2js(string $regex, string $statementType=JSHelper::JS_REGEX_OBJECT) : string
642
    {
643
        return JSHelper::buildRegexStatement($regex, $statementType);
644
    }
645
    
646
   /**
647
    * Converts the specified variable to JSON. Works just
648
    * like the native `json_encode` method, except that it
649
    * will trigger an exception on failure, which has the 
650
    * json error details included in its developer details.
651
    * 
652
    * @param mixed $variable
653
    * @param int $options JSON encode options.
654
    * @param int $depth 
655
    * @return string
656
    *
657
    * @throws ConvertHelper_Exception
658
    * @see ConvertHelper::ERROR_JSON_ENCODE_FAILED
659
    */
660
    public static function var2json($variable, int $options=0, int $depth=512) : string
661
    {
662
        $result = json_encode($variable, $options, $depth);
663
        
664
        if($result !== false) {
665
            return $result;
666
        }
667
        
668
        throw new ConvertHelper_Exception(
669
            'Could not create json array'.json_last_error_msg(),
670
            sprintf(
671
                'The call to json_encode failed for the variable [%s]. JSON error details: #%s, %s',
672
                parseVariable($variable)->toString(),
673
                json_last_error(),
674
                json_last_error_msg()
675
            ),
676
            self::ERROR_JSON_ENCODE_FAILED
677
        );
678
    }
679
680
    /**
681
     * Converts any PHP variable to a human-readable
682
     * string representation, like "object ClassName"
683
     *
684
     * @param mixed $variable
685
     * @return string
686
     */
687
    public function var2string($variable) : string
688
    {
689
        return parseVariable($variable)
690
            ->enableType()
691
            ->toString();
692
    }
693
    
694
   /**
695
    * Strips all known UTF byte order marks from the specified string.
696
    * 
697
    * @param string $string
698
    * @return string
699
    */
700
    public static function stripUTFBom(string $string) : string
701
    {
702
        $boms = FileHelper::getUTFBOMs();
703
704
        foreach($boms as $bomChars)
705
        {
706
            $length = mb_strlen($bomChars);
707
            $text = mb_substr($string, 0, $length);
708
709
            if($text===$bomChars)
710
            {
711
                return mb_substr($string, $length);
712
            }
713
        }
714
        
715
        return $string;
716
    }
717
718
   /**
719
    * Converts a string to valid utf8, regardless
720
    * of the string's encoding(s).
721
    * 
722
    * @param string $string
723
    * @return string
724
    */
725
    public static function string2utf8(string $string) : string
726
    {
727
        return ConvertHelper_String::toUtf8($string);
728
    }
729
    
730
   /**
731
    * Checks whether the specified string is an ASCII
732
    * string, without any special or UTF8 characters.
733
    * Note: empty strings and NULL are considered ASCII.
734
    * Any variable types other than strings are not.
735
    * 
736
    * @param string|float|int|NULL $string
737
    * @return boolean
738
    */
739
    public static function isStringASCII($string) : bool
740
    {
741
        return ConvertHelper_String::isASCII(strval($string));
742
    }
743
    
744
   /**
745
    * Adds HTML syntax highlighting to an URL.
746
    * 
747
    * NOTE: Includes the necessary CSS styles. When
748
    * highlighting several URLs in the same page,
749
    * prefer using the `parseURL` function instead.
750
    * 
751
    * @param string $url
752
    * @return string
753
    * @deprecated Use the Highlighter class directly instead.
754
    * @see Highlighter
755
    */
756
    public static function highlight_url(string $url) : string
757
    {
758
        return Highlighter::url($url);
759
    }
760
761
   /**
762
    * Calculates a percentage match of the source string with the target string.
763
    * 
764
    * Options are:
765
    * 
766
    * - maxLevenshtein, default: 10
767
    *   Any levenshtein results above this value are ignored.
768
    *   
769
    * - precision, default: 1
770
    *   The precision of the percentage float value
771
    * 
772
    * @param string $source
773
    * @param string $target
774
    * @param array<string,mixed> $options
775
    * @return float
776
    *
777
    * @see ConvertHelper_TextComparer
778
    * @see ConvertHelper_TextComparer::OPTION_MAX_LEVENSHTEIN_DISTANCE
779
    * @see ConvertHelper_TextComparer::OPTION_PRECISION
780
    */
781
    public static function matchString(string $source, string $target, array $options=array()) : float
782
    {
783
        return (new ConvertHelper_TextComparer())
784
            ->setOptions($options)
785
            ->match($source, $target);
786
    }
787
    
788
   /**
789
    * Converts a date interval to a human-readable string with
790
    * all necessary time components, e.g. "1 year, 2 months and 4 days".
791
    * 
792
    * @param DateInterval $interval
793
    * @return string
794
    * @see ConvertHelper_IntervalConverter
795
    *
796
    * @throws ConvertHelper_Exception
797
    * @see ConvertHelper_IntervalConverter::ERROR_MISSING_TRANSLATION
798
    */
799
    public static function interval2string(DateInterval $interval) : string
800
    {
801
        return (new ConvertHelper_IntervalConverter())
802
            ->toString($interval);
803
    }
804
    
805
   /**
806
    * Converts an interval to its total amount of days.
807
    * @param DateInterval $interval
808
    * @return int
809
    */
810
    public static function interval2days(DateInterval $interval) : int
811
    {
812
        return ConvertHelper_DateInterval::toDays($interval);
813
    }
814
815
   /**
816
    * Converts an interval to its total amount of hours.
817
    * @param DateInterval $interval
818
    * @return int
819
    */
820
    public static function interval2hours(DateInterval $interval) : int
821
    {
822
        return ConvertHelper_DateInterval::toHours($interval);
823
    }
824
    
825
   /**
826
    * Converts an interval to its total amount of minutes. 
827
    * @param DateInterval $interval
828
    * @return int
829
    */
830
    public static function interval2minutes(DateInterval $interval) : int
831
    {
832
        return ConvertHelper_DateInterval::toMinutes($interval);
833
    }
834
    
835
   /**
836
    * Converts an interval to its total amount of seconds.
837
    * @param DateInterval $interval
838
    * @return int
839
    */    
840
    public static function interval2seconds(DateInterval $interval) : int
841
    {
842
        return ConvertHelper_DateInterval::toSeconds($interval);
843
    }
844
    
845
   /**
846
    * Calculates the total amount of days / hours / minutes or seconds
847
    * of a date interval object (depending on the specified units), and
848
    * returns the total amount.
849
    * 
850
    * @param DateInterval $interval
851
    * @param string $unit What total value to calculate.
852
    * @return integer
853
    * 
854
    * @see ConvertHelper::INTERVAL_SECONDS
855
    * @see ConvertHelper::INTERVAL_MINUTES
856
    * @see ConvertHelper::INTERVAL_HOURS
857
    * @see ConvertHelper::INTERVAL_DAYS
858
    */
859
    public static function interval2total(DateInterval $interval, string $unit=self::INTERVAL_SECONDS) : int
860
    {
861
        return ConvertHelper_DateInterval::toTotal($interval, $unit);
862
    }
863
864
   /**
865
    * Converts a date to the corresponding day name.
866
    * 
867
    * @param DateTime $date
868
    * @param bool $short
869
    * @return string|NULL
870
    */
871
    public static function date2dayName(DateTime $date, bool $short=false) : ?string
872
    {
873
        return ConvertHelper_Date::toDayName($date, $short);
874
    }
875
    
876
   /**
877
    * Retrieves a list of english day names.
878
    * @return string[]
879
    */
880
    public static function getDayNamesInvariant() : array
881
    {
882
        return ConvertHelper_Date::getDayNamesInvariant();
883
    }
884
    
885
   /**
886
    * Retrieves the day names list for the current locale.
887
    * 
888
    * @param bool $short
889
    * @return string[]
890
    */
891
    public static function getDayNames(bool $short=false) : array
892
    {
893
        return ConvertHelper_Date::getDayNames($short);
894
    }
895
896
    /**
897
     * Implodes an array with a separator character, and the last item with "add".
898
     * 
899
     * @param string[] $list The indexed array with items to implode.
900
     * @param string $sep The separator character to use.
901
     * @param string $conjunction The word to use as conjunction with the last item in the list. NOTE: include spaces as needed.
902
     * @return string
903
     */
904
    public static function implodeWithAnd(array $list, string $sep = ', ', string $conjunction = '') : string
905
    {
906
        return ConvertHelper_Array::implodeWithAnd($list, $sep, $conjunction);
907
    }
908
    
909
   /**
910
    * Splits a string into an array of all characters it is composed of.
911
    * Unicode character safe.
912
    * 
913
    * NOTE: Spaces and newlines (both \r and \n) are also considered single
914
    * characters.
915
    * 
916
    * @param string $string
917
    * @return string[]
918
    */
919
    public static function string2array(string $string) : array
920
    {
921
        return ConvertHelper_String::toArray($string);
0 ignored issues
show
Bug Best Practice introduced by
The expression return AppUtils\ConvertH...tring::toArray($string) returns an array which contains values of type array which are incompatible with the documented value type string.
Loading history...
922
    }
923
    
924
   /**
925
    * Checks whether the specified string contains HTML code.
926
    * 
927
    * @param string $string
928
    * @return boolean
929
    */
930
    public static function isStringHTML(string $string) : bool
931
    {
932
        return ConvertHelper_String::isHTML($string);
933
    }
934
    
935
   /**
936
    * UTF8-safe wordwrap method: works like the regular wordwrap
937
    * PHP function but compatible with UTF8. Otherwise the lengths
938
    * are not calculated correctly.
939
    * 
940
    * @param string $str
941
    * @param int $width
942
    * @param string $break
943
    * @param bool $cut
944
    * @return string
945
    */
946
    public static function wordwrap(string $str, int $width = 75, string $break = "\n", bool $cut = false) : string 
947
    {
948
        return ConvertHelper_String::wordwrap($str, $width, $break, $cut);
949
    }
950
    
951
   /**
952
    * Calculates the byte length of a string, taking into 
953
    * account any unicode characters.
954
    * 
955
    * @param string $string
956
    * @return int
957
    */
958
    public static function string2bytes(string $string): int
959
    {
960
        return ConvertHelper_String::toBytes($string);
961
    }
962
    
963
   /**
964
    * Creates a short, 8-character long hash for the specified string.
965
    * 
966
    * WARNING: Not cryptographically safe.
967
    * 
968
    * @param string $string
969
    * @return string
970
    */
971
    public static function string2shortHash(string $string) : string
972
    {
973
        return ConvertHelper_String::toShortHash($string);
974
    }
975
976
    /**
977
     * Converts a string into an MD5 hash.
978
     *
979
     * @param string $string
980
     * @return string
981
     */
982
    public static function string2hash(string $string): string
983
    {
984
        return ConvertHelper_String::toHash($string);
985
    }
986
987
    /**
988
     * Converts the specified callable to string.
989
     *
990
     * NOTE: Will work even if the callable is not
991
     * actually callable, as compared to
992
     * `parseVariable($callback)->toString()`.
993
     *
994
     * @param callable $callback
995
     * @return string
996
     */
997
    public static function callback2string($callback) : string
998
    {
999
        // We are creating the renderer manually, to allow rendering
1000
        // callbacks to string even if they are not actually callable.
1001
        $renderer = new VariableInfo_Renderer_String_Callable(parseVariable($callback));
1002
1003
        return $renderer->render();
1004
    }
1005
1006
    public static function exception2info(\Throwable $e) : ConvertHelper_ThrowableInfo
1007
    {
1008
        return self::throwable2info($e);
1009
    }
1010
    
1011
    public static function throwable2info(\Throwable $e) : ConvertHelper_ThrowableInfo
1012
    {
1013
        return ConvertHelper_ThrowableInfo::fromThrowable($e);
1014
    }
1015
    
1016
   /**
1017
    * Parses the specified query string like the native 
1018
    * function <code>parse_str</code>, without the key
1019
    * naming limitations.
1020
    * 
1021
    * Using parse_str, dots or spaces in key names are 
1022
    * replaced by underscores. This method keeps all names
1023
    * intact.
1024
    * 
1025
    * It still uses the parse_str implementation as it 
1026
    * is tested and tried, but fixes the parameter names
1027
    * after parsing, as needed.
1028
    * 
1029
    * @param string $queryString
1030
    * @return array<string,string>
1031
    * @see ConvertHelper_QueryParser
1032
    */
1033
    public static function parseQueryString(string $queryString) : array
1034
    {
1035
        $parser = new ConvertHelper_QueryParser();
1036
        return $parser->parse($queryString);
1037
    }
1038
1039
   /**
1040
    * Searches for needle in the specified string, and returns a list
1041
    * of all occurrences, including the matched string. The matched 
1042
    * string is useful when doing a case-insensitive search, as it
1043
    * shows the exact matched case of needle.
1044
    *   
1045
    * @param string $needle
1046
    * @param string $haystack
1047
    * @param bool $caseInsensitive
1048
    * @return ConvertHelper_StringMatch[]
1049
    */
1050
    public static function findString(string $needle, string $haystack, bool $caseInsensitive=false): array
1051
    {
1052
        return ConvertHelper_String::findString($needle, $haystack, $caseInsensitive);
1053
    }
1054
    
1055
   /**
1056
    * Like explode, but trims all entries, and removes 
1057
    * empty entries from the resulting array.
1058
    * 
1059
    * @param string $delimiter
1060
    * @param string $string
1061
    * @return string[]
1062
    */
1063
    public static function explodeTrim(string $delimiter, string $string) : array
1064
    {
1065
        return ConvertHelper_String::explodeTrim($delimiter, $string);
1066
    }
1067
    
1068
   /**
1069
    * Detects the most used end-of-line character in the subject string.
1070
    * 
1071
    * @param string $subjectString The string to check.
1072
    * @return NULL|ConvertHelper_EOL The detected EOL instance, or NULL if none has been detected.
1073
    */
1074
    public static function detectEOLCharacter(string $subjectString) : ?ConvertHelper_EOL
1075
    {
1076
        return ConvertHelper_EOL::detect($subjectString);
1077
    }
1078
1079
   /**
1080
    * Removes the specified keys from the target array,
1081
    * if they exist.
1082
    * 
1083
    * @param array<string|int,mixed> $array
1084
    * @param string[] $keys
1085
    */
1086
    public static function arrayRemoveKeys(array &$array, array $keys) : void
1087
    {
1088
        ConvertHelper_Array::removeKeys($array, $keys);
1089
    }
1090
    
1091
   /**
1092
    * Checks if the specified variable is an integer or a string containing an integer.
1093
    * Accepts both positive and negative integers.
1094
    * 
1095
    * @param mixed $value
1096
    * @return bool
1097
    */
1098
    public static function isInteger($value) : bool
1099
    {
1100
        if(is_int($value)) {
1101
            return true;
1102
        }
1103
        
1104
        // booleans get converted to numbers, so they would
1105
        // actually match the regex.
1106
        if(is_bool($value)) {
1107
            return false;
1108
        }
1109
        
1110
        if(is_string($value) && $value !== '') {
1111
            return preg_match('/\A-?\d+\z/', $value) === 1;
1112
        }
1113
        
1114
        return false;    
1115
    }
1116
    
1117
   /**
1118
    * Converts an amount of seconds to a DateInterval object.
1119
    * 
1120
    * @param int $seconds
1121
    * @return DateInterval
1122
    * @throws ConvertHelper_Exception If the date interval cannot be created.
1123
    * 
1124
    * @see ConvertHelper::ERROR_CANNOT_GET_DATE_DIFF
1125
    */
1126
    public static function seconds2interval(int $seconds) : DateInterval
1127
    {
1128
        return ConvertHelper_DateInterval::fromSeconds($seconds)->getInterval();
1129
    }
1130
    
1131
   /**
1132
    * Converts a size string like "50 MB" to the corresponding byte size.
1133
    * It is case-insensitive, ignores spaces, and supports both traditional
1134
    * "MB" and "MiB" notations.
1135
    * 
1136
    * @param string $size
1137
    * @return int
1138
    */
1139
    public static function size2bytes(string $size) : int
1140
    {
1141
        return self::parseSize($size)->toBytes();
1142
    }
1143
    
1144
   /**
1145
    * Parses a size string like "50 MB" and returns a size notation instance
1146
    * that has utility methods to access information on it, and convert it.
1147
    * 
1148
    * @param string $size
1149
    * @return ConvertHelper_SizeNotation
1150
    */
1151
    public static function parseSize(string $size) : ConvertHelper_SizeNotation
1152
    {
1153
        return new ConvertHelper_SizeNotation($size);
1154
    }
1155
    
1156
   /**
1157
    * Creates a URL finder instance, which can be used to find
1158
    * URLs in a string - be it plain text, or HTML.
1159
    * 
1160
    * @param string $subject
1161
    * @return ConvertHelper_URLFinder
1162
    */
1163
    public static function createURLFinder(string $subject) : ConvertHelper_URLFinder
1164
    {
1165
        return new ConvertHelper_URLFinder($subject);
1166
    }
1167
1168
    /**
1169
     * Removes the target values from the source array.
1170
     *
1171
     * @param array<number|string,mixed> $sourceArray
1172
     * @param array<number|string,mixed> $values
1173
     * @param bool $keepKeys
1174
     * @return array<number|string,mixed>
1175
     */
1176
    public static function arrayRemoveValues(array $sourceArray, array $values, bool $keepKeys=false) : array
1177
    {
1178
        return ConvertHelper_Array::removeValues($sourceArray, $values, $keepKeys);
1179
    }
1180
}
1181