Completed
Push — master ( e23a18...07630d )
by Tilita
27:32
created

CompoundWordConvertor   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 3
lcom 0
cbo 0
dl 0
loc 44
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A convertToCamelCase() 0 4 1
A convertToPascalCase() 0 8 1
A convertToSnakeCase() 0 12 1
1
<?php
2
/**
3
 * This file is part of the NeedleProject\Common package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
namespace NeedleProject\Common\Convertor;
9
10
/**
11
 * Class CompoundWordConvertor
12
 *
13
 * @package NeedleProject\Common\Convertor
14
 * @author Adrian Tilita <[email protected]>
15
 * @copyright 2018 Adrian Tilita
16
 * @license https://opensource.org/licenses/MIT MIT Licence
17
 */
18
class CompoundWordConvertor
19
{
20
    /**
21
     * Convert any string to camelCase
22
     * @param string $word
23
     * @return string
24
     */
25 5
    public static function convertToCamelCase($word)
26
    {
27 5
        return lcfirst(self::convertToPascalCase($word));
28
    }
29
30
    /**
31
     * Convert any string to PascalCase
32
     * @param string $word
33
     * @return string
34
     */
35 10
    public static function convertToPascalCase($word)
36
    {
37
        // separate into block for easier readability
38 10
        $word = str_replace('_', ' ', $word);
39 10
        $word = strtolower($word);
40 10
        $word = ucwords($word);
41 10
        return str_replace(' ', '', $word);
42
    }
43
44
    /**
45
     * Convert any string to underscore_string (snake_case)
46
     * @param string $word
47
     * @return string
48
     */
49 4
    public static function convertToSnakeCase($word)
50
    {
51
        // append an _ to all capital letters. Ex: Abc will be converted to _Abc
52 4
        $word = preg_replace('/(?<!^)[A-Z]/', '_$0', $word);
53
        // replace spaces to underscore
54 4
        $word = preg_replace('/\s/','_', $word);
55
        // replace multiple spaces to one underscore
56 4
        $word = preg_replace('/\s\s+/','_', $word);
57
        // replace multiple underscores to one underscore
58 4
        $word = preg_replace('/([_]+)/','_', $word);
59 4
        return strtolower($word);
60
    }
61
}
62