CaseConverter::toPascalCase()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Selami\Stdlib;
6
7
use function lcfirst;
8
use function mb_convert_case;
9
use function mb_strtolower;
10
use function preg_replace;
11
use function str_replace;
12
use function trim;
13
14
use const MB_CASE_TITLE;
15
16
class CaseConverter
17
{
18
    /**
19
     * Returns PascalCase string
20
     */
21
    public static function toPascalCase(string $source, string $separator = '_'): string
22
    {
23
        // If the string is snake case
24
        $modified              = str_replace($separator, ' ', $source);
25
        $lowercase             = mb_strtolower($modified);
26
        $uppercaseFirstLetters = mb_convert_case($lowercase, MB_CASE_TITLE);
27
28
        return str_replace(' ', '', $uppercaseFirstLetters);
29
    }
30
31
    /**
32
     * Returns camelCase string
33
     */
34
    public static function toCamelCase(string $source, string $separator = '_'): string
35
    {
36
        return lcfirst(self::toPascalCase($source, $separator));
37
    }
38
39
    /**
40
     * Returns snake_case string
41
     */
42
    public static function toSnakeCase(string $source, string $separator = '_'): string
43
    {
44
        // If the string is pascal/camel case
45
        $modified  = str_replace('  ', ' ', preg_replace('/[A-Z]+/', ' $0', $source));
46
        $lowercase = mb_strtolower(trim($modified));
47
48
        return str_replace(' ', $separator, $lowercase);
49
    }
50
}
51