Passed
Push — master ( fd5fbe...6ba584 )
by Sebastian
03:41
created

ConvertHelper::boolStrict2string()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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