Completed
Pull Request — master (#143)
by Christoffer
03:20 queued 38s
created

ConfigAwareTrait::getConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
c 0
b 0
f 0
rs 10
cc 1
eloc 1
nc 1
nop 0
1
<?php
2
3
namespace Digia\GraphQL\Config;
4
5
trait ConfigAwareTrait
6
{
7
    /**
8
     * @var array
9
     */
10
    private $config;
11
12
    /**
13
     * ConfigAwareTrait constructor.
14
     * @param array $config
15
     */
16
    public function __construct(array $config = [])
17
    {
18
        $this->beforeConfig();
19
        $this->setConfig($config);
20
        $this->afterConfig();
21
    }
22
23
    /**
24
     * @param string     $key
25
     * @param mixed|null $default
26
     * @return mixed|null
27
     */
28
    public function getConfigValue(string $key, $default = null)
29
    {
30
        return $this->config[$key] ?? $default;
31
    }
32
33
    /**
34
     * @param string $key
35
     * @param mixed  $value
36
     * @return $this
37
     */
38
    public function setConfigValue(string $key, $value)
39
    {
40
        $this->config[$key] = $value;
41
        return $this;
42
    }
43
44
    /**
45
     * Override this method to perform logic BEFORE configuration is applied.
46
     * This method is useful for setting default values for properties.
47
     * However, remember to call the parent implementation if you do.
48
     */
49
    protected function beforeConfig(): void
50
    {
51
    }
52
53
    /**
54
     * Override this method to perform logic AFTER configuration is applied.
55
     * This method is useful for configuring classes after instantiation,
56
     * e.g. adding a query type to a schema.
57
     * However, remember to call the parent implementation if you do.
58
     */
59
    protected function afterConfig(): void
60
    {
61
    }
62
63
    /**
64
     * @param array $config
65
     * @return $this
66
     */
67
    protected function setConfig(array $config)
68
    {
69
        foreach ($config as $key => $value) {
70
            $setter = 'set' . ucfirst($key);
71
            if (method_exists($this, $setter)) {
72
                $this->$setter($value);
73
            } elseif (property_exists($this, $key)) {
74
                $this->$key = $value;
75
            }
76
        }
77
78
        $this->config = $config;
79
80
        return $this;
81
    }
82
}
83