Passed
Pull Request — master (#23)
by Christoffer
02:07 queued 19s
created

ConfigTrait::getConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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