Completed
Push — master ( 975e5f...c66b28 )
by Andreas
02:21
created

Str::startsWith()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 2
crap 1
1
<?php
2
/**
3
 * Utils.
4
 *
5
 * @copyright Copyright (c) 2016 Starweb / Ehandelslogik i Lund AB
6
 * @license   BSD 3-Clause
7
 */
8
9
namespace Starlit\Utils;
10
11
/**
12
 * String utilities.
13
 *
14
 * @author Andreas Nilsson <http://github.com/jandreasn>
15
 */
16
class Str
17
{
18
    /**
19
     * CamelCases words or a dash name  (eg. "hey-you" or "hey you" becomes "heyYou").
20
     * NB! This method is only for property formatted separated none
21
     * multibyte (UTF-8) ASCII strings. It doesn't handle malformed strings with
22
     * a lot of other weird characters.
23
     *
24
     * @param string $separatorString
25
     * @param string $separator
26
     * @param bool   $upperCamelCase If first character should be capitalized (eg. "HeyYou" instead of "heyYou")
27
     * @return string
28
     */
29 2
    public static function separatorToCamel($separatorString, $separator = '_', $upperCamelCase = false)
30
    {
31
        // Using PHP's built in functions seem to be a bit 30% faster than a regular expression replace
32 2
        $wordStr = str_replace($separator, ' ', strtolower($separatorString));
33 2
        $wordsCapitalized = ucwords($wordStr);
34 2
        $camelCased = str_replace(' ', '', $wordsCapitalized);
35
36 2
        return $upperCamelCase ? $camelCased : lcfirst($camelCased);
37
    }
38
39
    /**
40
     * Converts CamelCase text to lowercase separator separated text (eg. "heyYou" becomes "hey-you").
41
     * NB! This method is only for none multibyte (UTF-8) ASCII strings.
42
     *
43
     * @param string $camelCaseString
44
     * @param string $separator
45
     * @return string
46
     */
47 1
    public static function camelToSeparator($camelCaseString, $separator = '_')
48
    {
49 1
        $separatedString = preg_replace('/([a-zA-Z])([A-Z])/', '$1' . $separator . '$2', $camelCaseString);
50 1
        $separatedString = preg_replace('/([A-Z0-9])([A-Z])/', '$1' . $separator . '$2', $separatedString);
51
52 1
        return strtolower($separatedString);
53
    }
54
55
    /**
56
     * Get a random string generated from provided values.
57
     *
58
     * @param int    $charCount
59
     * @param string $characters
60
     * @return string
61
     */
62 1
    public static function random($charCount, $characters = 'abcdefghijklmnopqrstuvqxyz0123456789')
63
    {
64 1
        $randomString = '';
65 1
        for ($i = 0; $i < $charCount; $i++) {
66 1
            $pos = mt_rand(0, strlen($characters) - 1);
67 1
            $randomString .= $characters[$pos];
68 1
        }
69
70 1
        return $randomString;
71
    }
72
73
    /**
74
     * Get shortened string.
75
     *
76
     * @param bool $string
77
     * @param int $maxLength
78
     * @param string $indicator
79
     * @return string
80
     */
81 1
    public static function truncate($string, $maxLength, $indicator = '...')
82
    {
83 1
        if (mb_strlen($string) > $maxLength) {
84 1
            $string = mb_substr($string, 0, $maxLength - mb_strlen($indicator)) . $indicator;
85 1
        }
86
87 1
        return $string;
88
    }
89
90
    /**
91
     * Check if a string start with another substring.
92
     *
93
     * @param string $string
94
     * @param string $search
95
     * @return bool
96
     */
97 3
    public static function startsWith($string, $search)
98
    {
99 3
        return strpos($string, $search) === 0;
100
    }
101
102
    /**
103
     * Check if a string ends with another substring.
104
     *
105
     * @param string $string
106
     * @param string $search
107
     * @return bool
108
     */
109 4
    public static function endsWith($string, $search)
110
    {
111 4
        return (substr($string, -strlen($search)) === $search);
112
    }
113
114
    /**
115
     * Remove left part of string and return the new string.
116
     *
117
     * @param string $string
118
     * @param string $strip
119
     * @return string
120
     */
121 1
    public static function stripLeft($string, $strip)
122
    {
123 1
        if (self::startsWith($string, $strip)) {
124 1
            return substr($string, strlen($strip));
125
        }
126
127 1
        return $string;
128
    }
129
130
    /**
131
     * Remove right part of string and return the new string.
132
     *
133
     * @param string $string
134
     * @param string $strip
135
     * @return string
136
     */
137 2
    public static function stripRight($string, $strip)
138
    {
139 2
        if (self::endsWith($string, $strip)) {
140 2
            return substr($string, 0, -strlen($strip));
141
        }
142
143 1
        return $string;
144
    }
145
146
    /**
147
     * Increment a string/separated string.
148
     * Example: "a-name" becomes "a-name-2", "a-name-3" and so on.
149
     *
150
     * @param string $string
151
     * @param string $separator
152
     * @return string
153
     */
154 1
    public static function incrementSeparated($string, $separator = '-')
155
    {
156 1
        if (preg_match('/' . $separator . '(\d+)$/', $string, $matches)) {
157 1
            $string = self::stripRight($string, $separator . $matches[1]);
158 1
            $duplicateNo = ((int) $matches[1]) + 1;
159 1
        } else {
160 1
            $duplicateNo = 2;
161
        }
162
163 1
        $newString = $string . $separator . $duplicateNo;
164
165 1
        return $newString;
166
    }
167
168
    /**
169
     * @param string $string
170
     * @return string
171
     */
172 1
    public static function uppercaseFirst($string)
173
    {
174 1
        $length = mb_strlen($string);
175 1
        $firstChar = mb_substr($string, 0, 1);
176 1
        $otherChars = mb_substr($string, 1, $length - 1);
177
178 1
        return mb_strtoupper($firstChar) . $otherChars;
179
    }
180
181
    /**
182
     * Filter out all non numeric characters and return a clean numeric string.
183
     *
184
     * @param string $string
185
     * @param bool   $allowDecimal
186
     * @param bool   $allowNegative
187
     * @return string
188
     */
189 3
    public static function toNumber($string, $allowDecimal = false, $allowNegative = false)
190
    {
191 3
        $string = trim($string);
192
193 3
        $decimalPart = '';
194 3
        if (($firstPos = strpos($string, '.')) !== false) {
195 2
            $integerPart = substr($string, 0, $firstPos);
196 2
            if ($allowDecimal) {
197 1
                $rawDecimalPart = substr($string, $firstPos);
198 1
                $filteredDecimalPart = rtrim(preg_replace('/[^0-9]/', '', $rawDecimalPart), '0');
199 1
                if (!empty($filteredDecimalPart)) {
200 1
                    $decimalPart = '.' . $filteredDecimalPart;
201 1
                }
202 1
            }
203 2
        } else {
204 3
            $integerPart = $string;
205
        }
206
207 3
        $integerPart = ltrim(preg_replace('/[^0-9]/', '', $integerPart), '0');
208 3
        $integerPart = $integerPart ?: '0';
209
210 3
        $minusSign = '';
211 3
        if (strpos($string, '-') === 0) {
212 2
            if (!$allowNegative) {
213 1
                return '0';
214 1
            } elseif (!($integerPart === '0' && empty($decimalPart))) {
215 1
                $minusSign = '-';
216 1
            }
217 1
        }
218
219 3
        $number = $minusSign . $integerPart . $decimalPart;
220
221 3
        return $number;
222
    }
223
224
    /**
225
     * @param string $search
226
     * @param string $replace
227
     * @param string $subject
228
     * @return string
229
     */
230 2
    public static function replaceFirst($search, $replace, $subject)
231
    {
232 2
        if (($pos = strpos($subject, $search)) !== false) {
233 2
            return substr_replace($subject, $replace, $pos, strlen($search));
234
        }
235
236 1
        return $subject;
237
    }
238
}
239