Passed
Push — analysis-ne2BAG ( b838b8 )
by Arnaud
04:03 queued 11s
created

Str::strToBool()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 6
nc 4
nop 1
dl 0
loc 12
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Cecil\Util;
15
16
class Str
17
{
18
    /**
19
     * Converts an array to a string.
20
     *
21
     * ie: [0 => 'A', 1 => 'B'] become '0:A, 1:B'
22
     */
23
    public static function arrayToString(array $array, string $separator = ':'): string
24
    {
25
        $string = '';
26
27
        foreach ($array as $key => $value) {
28
            $string .= \sprintf('%s%s%s, ', $key, $separator, $value);
29
        }
30
31
        return substr($string, 0, -2);
32
    }
33
34
    /**
35
     * Combines an array into a string.
36
     *
37
     * @param string $keyToKey   The key that become the key of the new array
38
     * @param string $keyToValue The key that become the value of the new array
39
     * @param string $separator  The separtor between the key and the value in the result string
40
     */
41
    public static function combineArrayToString(
42
        array $array,
43
        string $keyToKey,
44
        string $keyToValue,
45
        string $separator = ':'
46
    ): string {
47
        $string = '';
48
49
        foreach ($array as $subArray) {
50
            $string .= \sprintf('%s%s%s, ', $subArray[$keyToKey], $separator, $subArray[$keyToValue]);
51
        }
52
53
        return substr($string, 0, -2);
54
    }
55
56
    /**
57
     * Converts 'true', 'false', 'on', 'off', 'yes', 'no' to a boolean.
58
     *
59
     * @return bool|mixed
60
     */
61
    public static function strToBool($value)
62
    {
63
        if (is_string($value)) {
64
            if (in_array($value, ['true', 'on', 'yes'])) {
65
                return true;
66
            }
67
            if (in_array($value, ['false', 'off', 'no'])) {
68
                return false;
69
            }
70
        }
71
72
        return $value;
73
    }
74
}
75