Passed
Push — master ( 13392a...6657cf )
by Arnaud
03:55 queued 10s
created

StringUtils::camelize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 9
rs 10
1
<?php
2
3
namespace LAG\Component\StringUtils;
4
5
class StringUtils
6
{
7
    /**
8
     * Camelize a string.
9
     *
10
     * @param string $id A string to camelize
11
     * @param bool   $lowerCase
12
     *
13
     * @return string The camelized string
14
     */
15
    public static function camelize(string $id, bool $lowerCase = false): string
16
    {
17
        $value = strtr(ucwords(strtr($id, ['_' => ' ', '.' => '_ ', '\\' => '_ '])), [' ' => '']);
18
19
        if ($lowerCase) {
20
            $value = strtolower($value);
21
        }
22
23
        return $value;
24
    }
25
26
    /**
27
     * A string to underscore.
28
     *
29
     * @param string $id The string to underscore
30
     *
31
     * @return string The underscored string
32
     */
33
    public static function underscore(string $id): string
34
    {
35
        return strtolower(preg_replace([
36
                '/([A-Z]+)([A-Z][a-z])/',
37
                '/([a-z\d])([A-Z])/',
38
            ], [
39
                '\\1_\\2',
40
                '\\1_\\2',
41
            ],
42
                str_replace('_', '.', $id))
43
        );
44
    }
45
46
    /**
47
     * Return the start of a string.
48
     *
49
     * @param string $string The string
50
     * @param int $length The number of characters
51
     *
52
     * @return string
53
     */
54
    public static function start(string $string, int $length = 1): string
55
    {
56
        return substr($string, 0, $length);
57
    }
58
59
    /**
60
     * Return the end of a string.
61
     *
62
     * @param string $string The string
63
     * @param int $length The number of characters
64
     *
65
     * @return string
66
     */
67
    public static function end(string $string, int $length = 1): string
68
    {
69
        return substr($string, -$length);
70
    }
71
72
    /**
73
     * Return true if the given string starts with $start.
74
     *
75
     * @param string $string
76
     * @param string $start
77
     *
78
     * @return bool
79
     */
80
    public static function startsWith(string $string, string $start): bool
81
    {
82
        return self::start($string, strlen($start)) === $start;
83
    }
84
85
    /**
86
     * Return true if the given string starts with $start.
87
     *
88
     * @param string $string
89
     * @param string $start
90
     *
91
     * @return bool
92
     */
93
    public static function endsWith(string $string, string $start): bool
94
    {
95
        return self::end($string, strlen($start)) === $start;
96
    }
97
}
98