Str::arrayToList()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of Cecil.
5
 *
6
 * (c) Arnaud Ligny <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Cecil\Util;
15
16
/**
17
 * String utility class.
18
 *
19
 * This class provides utility methods for string manipulation.
20
 */
21
class Str
22
{
23
    /**
24
     * Combines an array into a string.
25
     *
26
     * @param string $keyToKey   The key that become the key of the new array
27
     * @param string $keyToValue The key that become the value of the new array
28
     * @param string $separator  The separtor between the key and the value in the result string
29
     */
30
    public static function combineArrayToString(
31
        array $array,
32
        string $keyToKey,
33
        string $keyToValue,
34
        string $separator = ':'
35
    ): string {
36
        $string = '';
37
38
        foreach ($array as $subArray) {
39
            $string .= \sprintf('%s%s%s, ', $subArray[$keyToKey], $separator, $subArray[$keyToValue]);
40
        }
41
42
        return substr($string, 0, -2);
43
    }
44
45
    /**
46
     * Returns a string representation of an array.
47
     */
48
    public static function arrayToList(array $array): string
49
    {
50
        array_walk($array, function (&$value) {
51
            $value = \sprintf(" - %s", $value);
52
        });
53
54
        return implode("\n", $array);
55
    }
56
57
    /**
58
     * Converts 'true', 'false', 'on', 'off', 'yes', 'no' to a boolean.
59
     *
60
     * @param mixed $value Value to convert
61
     *
62
     * @return bool|mixed
63
     */
64
    public static function strToBool($value)
65
    {
66
        if (\is_string($value)) {
67
            if (\in_array($value, ['true', 'on', 'yes'])) {
68
                return true;
69
            }
70
            if (\in_array($value, ['false', 'off', 'no'])) {
71
                return false;
72
            }
73
        }
74
75
        return $value;
76
    }
77
78
    /**
79
     * Checks if a string starts with the given string.
80
     */
81
    public static function startsWith(string $haystack, string $needle): bool
82
    {
83
        $length = \strlen($needle);
84
85
        return substr($haystack, 0, $length) === $needle;
86
    }
87
88
    /**
89
     * Checks if a string ends with the given string.
90
     */
91
    public static function endsWith(string $haystack, string $needle): bool
92
    {
93
        $length = \strlen($needle);
94
        if (!$length) {
95
            return true;
96
        }
97
98
        return substr($haystack, -$length) === $needle;
99
    }
100
}
101