Passed
Push — master ( c64276...a08550 )
by Wilmer
28:17 queued 25:09
created

DbStringHelper::baseName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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