Completed
Push — 4.0 ( 268f2c...88f012 )
by Hideki
05:48 queued 10s
created

src/Eccube/Util/StringUtil.php (7 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.ec-cube.co.jp/
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 Eccube\Util;
15
16
use Doctrine\Common\Collections\ArrayCollection;
17
18
class StringUtil
19
{
20
    /**
21
     * The MIT License (MIT)
22
     *
23
     * Copyright (c) <Taylor Otwell>
24
     *
25
     * Permission is hereby granted, free of charge, to any person obtaining a copy
26
     * of this software and associated documentation files (the "Software"), to deal
27
     * in the Software without restriction, including without limitation the rights
28
     * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
29
     * copies of the Software, and to permit persons to whom the Software is
30
     * furnished to do so, subject to the following conditions:
31
     *
32
     * The above copyright notice and this permission notice shall be included in
33
     * all copies or substantial portions of the Software.
34
     *
35
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
36
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
37
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
38
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
39
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
40
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
41
     * THE SOFTWARE
42
     *
43
     * Generate a more truly "random" alpha-numeric string.
44
     *
45
     * @param  int $length
46
     *
47
     * @return string
48
     *
49
     * @throws \RuntimeException
50
     */
51 362
    public static function random($length = 16)
52
    {
53 362
        if (function_exists('openssl_random_pseudo_bytes')) {
54 362
            $bytes = openssl_random_pseudo_bytes($length * 2);
55
56 362
            if ($bytes === false) {
57 1
                throw new \RuntimeException('Unable to generate random string.');
58
            }
59
60 361
            return substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $length);
61
        }
62
63
        return static::quickRandom($length);
64
    }
65
66
    /**
67
     * The MIT License (MIT)
68
     *
69
     * Copyright (c) <Taylor Otwell>
70
     *
71
     * Permission is hereby granted, free of charge, to any person obtaining a copy
72
     * of this software and associated documentation files (the "Software"), to deal
73
     * in the Software without restriction, including without limitation the rights
74
     * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
75
     * copies of the Software, and to permit persons to whom the Software is
76
     * furnished to do so, subject to the following conditions:
77
     *
78
     * The above copyright notice and this permission notice shall be included in
79
     * all copies or substantial portions of the Software.
80
     *
81
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
82
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
83
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
84
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
85
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
86
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
87
     * THE SOFTWARE
88
     *
89
     * Generate a "random" alpha-numeric string.
90
     *
91
     * Should not be considered sufficient for cryptography, etc.
92
     *
93
     * @param  int $length
94
     *
95
     * @return string
96
     */
97 2
    public static function quickRandom($length = 16)
98
    {
99 2
        $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
100
101 2
        return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
102
    }
103
104
    /**
105
     * 改行コードの変換
106
     *
107
     * @param $value
108
     * @param string $lf
109
     *
110
     * @return string
111
     */
112 25
    public static function convertLineFeed($value, $lf = "\n")
113
    {
114 25
        if (empty($value)) {
115 1
            return '';
116
        }
117
118 24
        return strtr($value, array_fill_keys(["\r\n", "\r", "\n"], $lf));
119
    }
120
121
    /**
122
     * 文字コードの判定
123
     *
124
     * @param string $value
125
     *
126
     * @return string
127
     */
128 21
    public static function characterEncoding($value, $encoding = ['UTF-8', 'SJIS', 'EUC-JP', 'ASCII', 'JIS', 'sjis-win'])
129
    {
130 21
        foreach ($encoding as $encode) {
131 21
            if (mb_check_encoding($value, $encode)) {
132 21
                return $encode;
133
            }
134
        }
135
136 1
        return null;
137
    }
138
139
    /**
140
     * 指定した文字列以上ある場合、「...」を付加する
141
     * lengthに7を指定すると、「1234567890」は「1234567...」と「...」を付与して出力される
142
     *
143
     * @param string $value
144
     * @param int $length
145
     * @param string $end
146
     *
147
     * @return string
148
     */
149 2
    public static function ellipsis($value, $length = 100, $end = '...')
150
    {
151 2
        if (mb_strlen($value) <= $length) {
152 1
            return $value;
153
        }
154
155 1
        return rtrim(mb_substr($value, 0, $length, 'UTF-8')).$end;
156
    }
157
158
    /**
159
     * 現在からの経過時間を書式化する.
160
     *
161
     * @param $date
162
     *
163
     * @return string
164
     */
165 1
    public static function timeAgo($date)
166
    {
167 1
        if (empty($date)) {
168 1
            return '';
169
        }
170
171 1
        $now = new \DateTime();
172 1
        if (!($date instanceof \DateTime)) {
173 1
            $date = new \DateTime($date);
174
        }
175 1
        $diff = $date->diff($now, true);
176 1
        if ($diff->y > 0) {
177
            // return $date->format("Y/m/d H:i");
178 1
            return $date->format('Y/m/d');
179
        }
180 1
        if ($diff->m == 1 || $diff->days > 0) {
181 1
            if ($diff->days <= 31) {
182 1
                return $diff->days.'日前';
183
            }
184
            // return $date->format("Y/m/d H:i");
185 1
            return $date->format('Y/m/d');
186
        }
187 1
        if ($diff->h > 0) {
188 1
            return $diff->h.'時間前';
189
        }
190 1
        if ($diff->i > 0) {
191 1
            return $diff->i.'分前';
192
        }
193
194 1
        return $diff->s.'秒前';
195
    }
196
197
    /**
198
     * 変数が空白かどうかをチェックする.
199
     *
200
     * 引数 $value が空白かどうかをチェックする. 空白の場合は true.
201
     * 以下の文字は空白と判断する.
202
     * - ' ' (ASCII 32 (0x20)), 通常の空白
203
     * - "\t" (ASCII 9 (0x09)), タブ
204
     * - "\n" (ASCII 10 (0x0A)), リターン
205
     * - "\r" (ASCII 13 (0x0D)), 改行
206
     * - "\0" (ASCII 0 (0x00)), NULバイト
207
     * - "\x0B" (ASCII 11 (0x0B)), 垂直タブ
208
     *
209
     * 引数 $value がオブジェクト型、配列の場合は非推奨とし、 E_USER_DEPRECATED をスローする.
210
     * EC-CUBE2系からの互換性、ビギナー層を配慮し、以下のような実装とする.
211
     * 引数 $value が配列の場合は, 空の配列の場合 true を返す.
212
     * 引数 $value が ArrayCollection::isEmpty() == true の場合 true を返す.
213
     * 引数 $value が上記以外のオブジェクト型の場合は false を返す.
214
     *
215
     * 引数 $greedy が true の場合は, 全角スペース, ネストした空の配列も
216
     * 空白と判断する.
217
     *
218
     * @param string $value チェック対象の変数. 文字型以外も使用できるが、非推奨.
219
     * @param boolean $greedy '貧欲'にチェックを行う場合 true, デフォルト false
220
     *
221
     * @return boolean $value が空白と判断された場合 true
222
     */
223 97
    public static function isBlank($value, $greedy = false)
224
    {
225 97
        $deprecated = '\Eccube\Util\StringUtil::isBlank() の第一引数は文字型、数値を使用してください';
226
        // テストカバレッジを上げるために return の前で trigger_error をスローしている
227 97
        if (is_object($value)) {
228 3
            if ($value instanceof ArrayCollection) {
229 2
                if ($value->isEmpty()) {
230 1
                    @trigger_error($deprecated, E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
231
232 1
                    return true;
233
                } else {
234 1
                    @trigger_error($deprecated, E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
235
236 1
                    return false;
237
                }
238
            }
239 1
            @trigger_error($deprecated, E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
240
241 1
            return false;
242
        }
243 94
        if (is_array($value)) {
244 5
            if ($greedy) {
245 3
                if (empty($value)) {
246 1
                    @trigger_error($deprecated, E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
247
248 1
                    return true;
249
                }
250 2
                $array_result = true;
251 2
                foreach ($value as $in) {
252 2
                    $array_result = self::isBlank($in, $greedy);
253 2
                    if (!$array_result) {
254 1
                        @trigger_error($deprecated, E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
255
256 2
                        return false;
257
                    }
258
                }
259 1
                @trigger_error($deprecated, E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
260
261 1
                return $array_result;
262
            } else {
263 2
                @trigger_error($deprecated, E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
264
265 2
                return empty($value);
266
            }
267
        }
268
269 91
        if ($greedy) {
270 3
            $value = preg_replace('/ /', '', $value);
271
        }
272
273 91
        $value = trim($value);
274 91
        if (strlen($value) > 0) {
275 89
            return false;
276
        }
277
278 13
        return true;
279
    }
280
281
    /**
282
     * @param $value
283
     *
284
     * @return bool
285
     */
286 83
    public static function isNotBlank($value, $greedy = false)
287
    {
288 83
        return !self::isBlank($value, $greedy);
289
    }
290
291
    /**
292
     * 両端にある全角スペース、半角スペースを取り除く
293
     *
294
     * @param $value
295
     *
296
     * @return string
297
     */
298 13
    public static function trimAll($value)
299
    {
300 13
        if ($value === '') {
301 1
            return '';
302
        }
303 13
        if ($value === 0) {
304 1
            return 0;
305
        }
306 13
        if ($value == null) {
307 1
            return null;
308
        }
309
310 13
        return preg_replace('/(^\s+)|(\s+$)/u', '', $value);
311
    }
312
313
    /**
314
     * envファイルのコンテンツを更新または追加する.
315
     *
316
     * @param string $env
317
     * @param array $replacement
318
     *
319
     * @return string
320
     */
321 7
    public static function replaceOrAddEnv($env, array $replacement)
322
    {
323 7
        foreach ($replacement as $key => $value) {
324 7
            $pattern = '/^('.$key.')=(.*)/m';
325 7
            if (preg_match($pattern, $env)) {
326 4
                $env = preg_replace($pattern, '$1='.$value, $env);
327 4
                if ('\\' === DIRECTORY_SEPARATOR) {
328
                    // The m modifier of the preg functions converts the end-of-line to '\n'
329 4
                    $env = self::convertLineFeed($env, "\r\n");
330
                }
331
            } else {
332 7
                $env .= PHP_EOL."${key}=${value}";
333
            }
334
        }
335
336 7
        return $env;
337
    }
338
}
339