Passed
Push — master ( 800de6...ff9dd6 )
by Jean Paul
08:33
created

TextUtils::fromCamelToSnakeCase()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 8
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 13
rs 10
1
<?php
2
3
namespace Coco\SourceWatcher\Utils;
4
5
/**
6
 * Class TextUtils
7
 *
8
 * @package Coco\SourceWatcher\Utils
9
 */
10
class TextUtils
11
{
12
    public function textToCamelCase ( string $word ) : string
13
    {
14
        // Make an array of word parts exploding the word by "_"
15
        $wordParts = explode( "_", $word );
16
17
        // Make every word part lower case
18
        $wordParts = array_map( "strtolower", $wordParts );
19
20
        // Make every word part first character uppercase
21
        $wordParts = array_map( "ucfirst", $wordParts );
22
23
        // Make the new word the combination of the given word parts
24
        $newWord = implode( "", $wordParts );
25
26
        // Make the new word first character lowercase
27
        return lcfirst( $newWord );
28
    }
29
30
    public function textToPascalCase ( string $word ) : string
31
    {
32
        // Make an array of word parts exploding the word by "_"
33
        $wordParts = explode( "_", $word );
34
35
        // Make every word part lower case
36
        $wordParts = array_map( "strtolower", $wordParts );
37
38
        // Make every word part first character uppercase
39
        $wordParts = array_map( "ucfirst", $wordParts );
40
41
        // Make the new word the combination of the given word parts
42
        return implode( "", $wordParts );
43
    }
44
45
    public function fromCamelToSnakeCase ( string $word ) : string
46
    {
47
        $pattern = '!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!';
48
        preg_match_all( $pattern, $word, $matches );
49
        $ret = $matches[0];
50
51
        foreach ( $ret as &$match ) {
52
            $match = $match == strtoupper( $match ) ?
53
                strtolower( $match ) :
54
                lcfirst( $match );
55
        }
56
57
        return implode( '_', $ret );
58
    }
59
}
60