ParsesAttributes::fromCamelToSnake()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
/**
3
 * GetsSetsAttributes Trait
4
 */
5
namespace Twigger\UnionCloud\API\Traits;
6
7
use Carbon\Carbon;
8
9
/**
10
 * Helper functions for getting and setting  attributes in a class
11
 * when given by an array.
12
 *
13
 * This class was designed to aid with Resource development, in particular setting
14
 * and getting resource attributes. All attributes should be set using the property phpDoc
15
 * tag, and accessed through $this->camelCase.
16
 * e.g. $this->studentId
17
 *
18
 * It also allows for casting. Define a protected property $casts, which holds as
19
 * associative array. The key should be the camel cased attribute, and the
20
 * value should be one of
21
 *      'date' => returns a Carbon instance
22
 *
23
 * This will set the initial resource attributes to
24
 *
25
 *
26
 * @package Twigger\UnionCloud\API\Core\Traits
27
 */
28
trait ParsesAttributes
29
{
30
31
     /**
32
     * Convert camelCase to snake_case
33
     *
34
     * @param string $key
35
     *
36
     * @return string
37
     */
38
    public function fromCamelToSnake($key)
39
    {
40
        preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $key, $matches);
41
        $ret = $matches[0];
42
        foreach ($ret as &$match) {
43
            $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
44
        }
45
        return implode('_', $ret);
46
    }
47
48
    /**
49
     * Convert snake_case to camelCase
50
     *
51
     * @param string $key
52
     *
53
     * @return mixed
54
     */
55
    public function fromSnakeToCamel($key)
56
    {
57
        $key = str_replace('_', '', ucwords($key, '_'));
58
        $key = lcfirst($key);
59
        return $key;
60
    }
61
62
}