|
1
|
|
|
<?php
|
|
2
|
|
|
|
|
3
|
|
|
namespace common\helpers;
|
|
4
|
|
|
|
|
5
|
|
|
/**
|
|
6
|
|
|
* Class StringHelper
|
|
7
|
|
|
* @package common\helpers
|
|
8
|
|
|
*/
|
|
9
|
|
|
class StringHelper extends \yii\helpers\StringHelper
|
|
10
|
|
|
{
|
|
11
|
|
|
/**
|
|
12
|
|
|
* Первая буква - заглавная
|
|
13
|
|
|
*
|
|
14
|
|
|
* @param $string
|
|
15
|
|
|
* @param string $e
|
|
16
|
|
|
* @return string
|
|
17
|
|
|
*/
|
|
18
|
|
|
public static function ucfirst($string, $e = 'utf-8')
|
|
19
|
|
|
{
|
|
20
|
|
|
if (function_exists('mb_strtoupper') && function_exists('mb_substr') && !empty($string)) {
|
|
21
|
|
|
$string = mb_strtolower($string, $e);
|
|
22
|
|
|
$upper = mb_strtoupper($string, $e);
|
|
23
|
|
|
preg_match('#(.)#us', $upper, $matches);
|
|
24
|
|
|
$string = $matches[1] . mb_substr($string, 1, mb_strlen($string, $e), $e);
|
|
25
|
|
|
} else {
|
|
26
|
|
|
$string = ucfirst($string);
|
|
27
|
|
|
}
|
|
28
|
|
|
return $string;
|
|
29
|
|
|
}
|
|
30
|
|
|
|
|
31
|
|
|
/**
|
|
32
|
|
|
* Форматирует и конвертирует кол-во байт, возвращает строку
|
|
33
|
|
|
*
|
|
34
|
|
|
* Например: 9.54 MB
|
|
35
|
|
|
*
|
|
36
|
|
|
* @param $bytes
|
|
37
|
|
|
* @param int $precision
|
|
38
|
|
|
* @return string
|
|
39
|
|
|
*/
|
|
40
|
|
|
public static function formatBytes($bytes, $precision = 2)
|
|
41
|
|
|
{
|
|
42
|
|
|
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
|
43
|
|
|
$bytes = max($bytes, 0);
|
|
44
|
|
|
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
|
|
45
|
|
|
$pow = min($pow, count($units) - 1);
|
|
46
|
|
|
$bytes /= pow(1024, $pow);
|
|
47
|
|
|
return round($bytes, $precision) . ' ' . $units[$pow];
|
|
48
|
|
|
}
|
|
49
|
|
|
|
|
50
|
|
|
/**
|
|
51
|
|
|
* Генерация случайной строки
|
|
52
|
|
|
*
|
|
53
|
|
|
* @param int $length
|
|
54
|
|
|
* @param bool $allowUppercase
|
|
55
|
|
|
* @return string
|
|
56
|
|
|
*/
|
|
57
|
|
|
public static function generateRandomString($length = 8, $allowUppercase = true)
|
|
58
|
|
|
{
|
|
59
|
|
|
$validCharacters = 'abcdefghijklmnopqrstuxyvwz1234567890';
|
|
60
|
|
|
if ($allowUppercase) {
|
|
61
|
|
|
$validCharacters .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
62
|
|
|
}
|
|
63
|
|
|
$validCharNumber = strlen($validCharacters);
|
|
64
|
|
|
$result = '';
|
|
65
|
|
|
for ($i = 0; $i < $length; $i++) {
|
|
66
|
|
|
$index = mt_rand(0, $validCharNumber - 1);
|
|
67
|
|
|
$result .= $validCharacters[$index];
|
|
68
|
|
|
}
|
|
69
|
|
|
return $result;
|
|
70
|
|
|
}
|
|
71
|
|
|
}
|
|
72
|
|
|
|