Completed
Push — master ( c341af...a0246f )
by Christoffer
02:19 queued 18s
created

ConfigAwareTrait::beforeConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 2
c 0
b 0
f 0
rs 10
cc 1
eloc 0
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
     * @return array
46
     */
47
    public function getConfig(): array
48
    {
49
        return $this->config;
50
    }
51
52
    /**
53
     * Override this method to perform logic BEFORE configuration is applied.
54
     * This method is useful for setting default values for properties
55
     * that need to use new -keyword.
56
     * If you do, just remember to call the parent implementation.
57
     */
58
    protected function beforeConfig(): void
59
    {
60
    }
61
62
    /**
63
     * Override this method to perform logic AFTER configuration is applied.
64
     * This method is useful for configuring classes after instantiation,
65
     * e.g. adding a query type to a schema or adding fields to object types.
66
     * If you do, just remember to call the parent implementation.
67
     */
68
    protected function afterConfig(): void
69
    {
70
    }
71
72
    /**
73
     * @param array $config
74
     * @return $this
75
     */
76
    protected function setConfig(array $config)
77
    {
78
        foreach ($config as $key => $value) {
79
            $setter = 'set' . ucfirst($key);
80
81
            if (method_exists($this, $setter)) {
82
                $this->$setter($value);
83
            } elseif (property_exists($this, $key)) {
84
                $this->$key = $value;
85
            }
86
        }
87
88
        $this->config = $config;
89
90
        return $this;
91
    }
92
}
93