Passed
Pull Request — master (#481)
by Def
02:15
created

StringHelper   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 60
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A normalizeFloat() 0 8 2
A pascalCaseToId() 0 7 1
A baseName() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Helper;
6
7
final class StringHelper
8
{
9
    /**
10
     * Returns the trailing name component of a path.
11
     * This method is similar to the php function `basename()` except that it will
12
     * treat both \ and / as directory separators, independent of the operating system.
13
     * This method was mainly created to work on php namespaces. When working with real
14
     * file paths, PHP's `basename()` should work fine for you.
15
     * Note: this method is not aware of the actual filesystem, or path components such as "..".
16
     *
17
     * @param string $path A path string.
18
     *
19
     * @return string The trailing name component of the given path.
20
     *
21
     * @see http://www.php.net/manual/en/function.basename.php
22
     */
23
    public static function baseName(string $path): string
24
    {
25
        $path = rtrim(str_replace('\\', '/', $path), '/\\');
26
        $position = mb_strrpos($path, '/');
27
        if ($position !== false) {
28
            return mb_substr($path, $position + 1);
29
        }
30
31
        return $path;
32
    }
33
34
    /**
35
     * Returns string representation of a number value without thousands separators and with dot as decimal separator.
36
     *
37
     * @param float|string $value
38
     *
39
     * @return string
40
     */
41
    public static function normalizeFloat(float|string $value): string
42
    {
43
        if (is_float($value)) {
44
            $value = (string)$value;
45
        }
46
47
        $value = str_replace([' ', ','], ['', '.'], $value);
48
        return preg_replace('/\.(?=.*\.)/', '', $value);
49
    }
50
51
    /**
52
     * Converts a PascalCase name into an ID in lowercase.
53
     * Words in the ID may be concatenated using '_'.
54
     * For example, 'PostTag' will be converted to 'post_tag'.
55
     *
56
     * @param string $input The string to be converted.
57
     *
58
     * @return string The resulting ID.
59
     */
60
    public static function pascalCaseToId(string $input): string
61
    {
62
        $separator = '_';
63
64
        $result = preg_replace('/(?<=\p{L})(?<!\p{Lu})(\p{Lu})/u', addslashes($separator) . '\1', $input);
65
66
        return mb_strtolower(trim($result, $separator));
67
    }
68
}
69