CompoundWordConvertor::convertToCamelCase()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 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
     * Check if a string is camelCase
22
     *
23
     * @param string $item
24
     * @return bool
25 5
     */
26
    public static function isCamelCase($item)
27 5
    {
28
        // validates if it starts with an uppercase or contains one of the separator: space, _ or -
29
        preg_match('/^([A-Z]{1})|([\-_\s]+)/msU', $item, $results);
30
        return empty($results);
31
    }
32
33
    /**
34
     * Convert to camelCase
35 10
     *
36
     * @param $word
37
     * @return string
38 10
     */
39 10
    public static function convertToCamelCase($word)
40 10
    {
41 10
        return lcfirst(self::convertToPascalCase($word));
42
    }
43
44
    /**
45
     * Convert any string to PascalCase
46
     * @param string $word
47
     * @return string
48
     */
49 4
    public static function convertToPascalCase($word)
50
    {
51
/*        if (self::isPascalCase($word)) {
52 4
            return $word;
53
        }
54 4
*/
55
        // separate into block for easier readability
56 4
        $word = str_replace('_', ' ', $word);
57
        $word = strtolower($word);
58 4
        $word = ucwords($word);
59 4
        return str_replace(' ', '', $word);
60
    }
61
62
    /**
63
     * Convert any string to underscore_string (snake_case)
64
     * @param string $word
65
     * @return string
66
     */
67
    public static function convertToSnakeCase($word)
68
    {
69
        // append an _ to all capital letters. Ex: Abc will be converted to _Abc
70
        $word = preg_replace('/(?<!^)[A-Z]/', '_$0', $word);
71
        // replace spaces to underscore
72
        $word = preg_replace('/\s/', '_', $word);
73
        // replace multiple spaces to one underscore
74
        $word = preg_replace('/\s\s+/', '_', $word);
75
        // replace multiple underscores to one underscore
76
        $word = preg_replace('/([_]+)/', '_', $word);
77
        return strtolower($word);
78
    }
79
}
80