Completed
Pull Request — master (#20)
by Steven
07:01 queued 05:18
created

ConfigurationTrait::parseConfiguration()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
3
namespace Stevenmaguire\Yelp\Tool;
4
5
trait ConfigurationTrait
6
{
7
    /**
8
     * Retrives the value of a given property from the client.
9
     *
10
     * @param  string  $property
11
     *
12
     * @return mixed|null
13
     */
14
    public function __get($property)
15
    {
16
        if (property_exists($this, $property)) {
17
            return $this->$property;
18
        }
19
20
        return null;
21
    }
22
23
    /**
24
     * Maps legacy configuration keys to updated keys.
25
     *
26
     * @param  array   $configuration
27
     *
28
     * @return array
29
     */
30
    protected function mapConfiguration(array $configuration)
31
    {
32
        array_walk($configuration, function ($value, $key) use (&$configuration) {
33
            $newKey = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key))));
34
            $configuration[$newKey] = $value;
35
        });
36
37
        return $configuration;
38
    }
39
40
    /**
41
     * Parse configuration using defaults
42
     *
43
     * @param  array $configuration
44
     * @param  array $defaults
45
     *
46
     * @return mixed
47
     */
48
    protected function parseConfiguration($configuration = [], $defaults = [])
49
    {
50
        $configuration = array_merge($defaults, $this->mapConfiguration($configuration));
51
52
        array_walk($configuration, [$this, 'setConfig']);
53
54
        return $this;
55
    }
56
57
    /**
58
     * Attempts to set a given value.
59
     *
60
     * @param mixed   $value
61
     * @param string  $key
62
     *
63
     * @return mixed
64
     */
65
    protected function setConfig($value, $key)
66
    {
67
        $setter = 'set' . ucfirst($key);
68
69
        if (method_exists($this, $setter)) {
70
            $this->$setter($value);
71
        } elseif (property_exists($this, $key)) {
72
            $this->$key = $value;
73
        }
74
75
        return $this;
76
    }
77
}
78