Builder   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 64
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A hydrate() 0 20 4
A studly() 0 11 2
A camel() 0 7 2
1
<?php
2
3
namespace Goldoni\Builder;
4
5
/**
6
 * Class Builder.
7
 */
8
class Builder
9
{
10
    /**
11
     * The cache of studly-cased words.
12
     *
13
     * @var array
14
     */
15
    protected static $studlyCache = [];
16
    /**
17
     * The cache of camel-cased words.
18
     *
19
     * @var array
20
     */
21
    protected static $camelCache = [];
22
23
    public static function hydrate(array $item, $object)
24
    {
25
        if (\is_string($object)) {
26
            $instance = new $object();
27
        } else {
28
            $instance = $object;
29
        }
30
31
        foreach ($item as $key => $value) {
32
            $method = 'set' . self::studly($key);
33
34
            if (method_exists($instance, $method)) {
35
                $instance->{$method}($value);
36
            } else {
37
                $property = self::camel($key);
38
                $instance->{$property} = $value;
39
            }
40
        }
41
42
        return $instance;
43
    }
44
45
    public static function studly($value)
46
    {
47
        $key = $value;
48
49
        if (isset(static::$studlyCache[$key])) {
50
            return static::$studlyCache[$key];
51
        }
52
53
        $value = ucwords(str_replace(['-', '_'], ' ', $value));
54
55
        return static::$studlyCache[$key] = str_replace(' ', '', $value);
56
    }
57
58
    /**
59
     * Convert a value to camel case.
60
     *
61
     * @param string $value
62
     *
63
     * @return string
64
     */
65
    public static function camel($value)
66
    {
67
        if (isset(static::$camelCache[$value])) {
68
            return static::$camelCache[$value];
69
        }
70
71
        return static::$camelCache[$value] = lcfirst(static::studly($value));
72
    }
73
}
74