Passed
Pull Request — master (#595)
by Def
11:30
created

StringHelper::toUuid()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 14
nc 4
nop 1
dl 0
loc 20
rs 9.4888
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Helper;
6
7
use Yiisoft\Db\Exception\InvalidArgumentException;
8
use function addslashes;
9
use function is_float;
10
use function mb_strrpos;
11
use function mb_strtolower;
12
use function mb_substr;
13
use function preg_replace;
14
use function rtrim;
15
use function str_replace;
16
use function trim;
17
18
/**
19
 * Short implementation of StringHelper from Yii2.
20
 */
21
final class StringHelper
22
{
23
    /**
24
     * Returns the trailing name part of a path.
25
     *
26
     * This method is similar to the php function `basename()` except that it will treat both \ and / as directory
27
     * separators, independent of the operating system.
28
     *
29
     * This method was mainly created to work on php namespaces. When working with real file paths, PHP's `basename()`
30
     * should work fine for you.
31
     *
32
     * Note: this method isn't aware of the actual filesystem, or path components such as "..".
33
     *
34
     * @param string $path A path string.
35
     *
36
     * @return string The trailing name part of the given path.
37
     *
38
     * @link http://www.php.net/manual/en/function.basename.php
39
     */
40
    public static function baseName(string $path): string
41
    {
42
        $path = rtrim(str_replace('\\', '/', $path), '/\\');
43
        $position = mb_strrpos($path, '/');
44
45
        if ($position !== false) {
46
            return mb_substr($path, $position + 1);
47
        }
48
49
        return $path;
50
    }
51
52
    /**
53
     * Returns string representation of a number value without a thousand separators and with dot as decimal separator.
54
     *
55
     * @param float|string $value The number value to be normalized.
56
     */
57
    public static function normalizeFloat(float|string $value): string
58
    {
59
        if (is_float($value)) {
60
            $value = (string) $value;
61
        }
62
63
        $value = str_replace([' ', ','], ['', '.'], $value);
64
        return preg_replace('/\.(?=.*\.)/', '', $value);
65
    }
66
67
    /**
68
     * Converts a PascalCase name into an ID in lowercase.
69
     *
70
     * Words in the ID may be concatenated using '_'. For example, 'PostTag' will be converted to 'post_tag'.
71
     *
72
     * @param string $input The string to be converted.
73
     *
74
     * @return string The resulting ID.
75
     */
76
    public static function pascalCaseToId(string $input): string
77
    {
78
        $separator = '_';
79
        $result = preg_replace('/(?<=\p{L})(?<!\p{Lu})(\p{Lu})/u', addslashes($separator) . '\1', $input);
80
        return mb_strtolower(trim($result, $separator));
81
    }
82
83
    public static function toUuid(string $blobString)
84
    {
85
        if (self::isValidUuid($blobString)) {
86
            return $blobString;
87
        }
88
89
        if (strlen($blobString) === 16) {
90
            $hex = bin2hex($blobString);
91
        } elseif(strlen($blobString) === 32 && self::isValidHexUuid($blobString)) {
92
            $hex = $blobString;
93
        } else {
94
            throw new InvalidArgumentException('Length of source data is should be 16 or 32 bytes.');
95
        }
96
97
        return
98
            substr($hex, 0, 8) . '-' .
99
            substr($hex, 8, 4) . '-' .
100
            substr($hex, 12, 4) . '-' .
101
            substr($hex, 16, 4) . '-' .
102
            substr($hex, 20)
103
        ;
104
    }
105
106
    public static function uuidToBlob(string $uuidString): string
107
    {
108
        if (!self::isValidUuid($uuidString)) {
109
            throw new InvalidArgumentException('Incorrect UUID.');
110
        }
111
112
        return (string) hex2bin(str_replace('-', '', $uuidString));
113
    }
114
115
    public static function isValidUuid(string $uuidString): bool
116
    {
117
        return (bool) preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $uuidString);
118
    }
119
120
    public static function isValidHexUuid(string $uuidString): bool
121
    {
122
        return (bool) preg_match('/^[0-9a-f]{32}$/i', $uuidString);
123
    }
124
}
125