ParsesAttributes   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 9
dl 0
loc 32
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A fromSnakeToCamel() 0 5 1
A fromCamelToSnake() 0 8 3
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
}