IntegrationConnections::find()   B
last analyzed

Complexity

Conditions 7
Paths 12

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
dl 0
loc 39
ccs 0
cts 34
cp 0
rs 8.3626
c 0
b 0
f 0
cc 7
nc 12
nop 2
crap 56
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipboxfactory/craft-integration/blob/master/LICENSE
6
 * @link       https://github.com/flipboxfactory/craft-integration/
7
 */
8
9
namespace flipbox\craft\integration\services;
10
11
use Craft;
12
use craft\helpers\ArrayHelper;
13
use craft\helpers\Component as ComponentHelper;
14
use flipbox\craft\integration\exceptions\ConnectionNotFound;
15
use Flipbox\Skeleton\Exceptions\InvalidConfigurationException;
16
use Flipbox\Skeleton\Helpers\ObjectHelper;
17
use yii\base\Component;
18
use yii\db\Query;
19
20
/**
21
 * @author Flipbox Factory <[email protected]>
22
 * @since 2.2.0
23
 */
24
abstract class IntegrationConnections extends Component
25
{
26
    /**
27
     * The app connection handle
28
     */
29
    const CONNECTION = 'app';
30
31
    /**
32
     * The default connection identifier
33
     */
34
    const DEFAULT_CONNECTION = 'DEFAULT';
35
36
    /**
37
     * The override file
38
     */
39
    public $overrideFile;
40
41
    /**
42
     * @var array|null
43
     */
44
    private $overrides;
45
46
    /**
47
     * @var array
48
     */
49
    private $connections = [];
50
51
    /**
52
     * @var array
53
     */
54
    private $enabled = [];
55
56
    /**
57
     * @return string
58
     */
59
    abstract protected static function tableName(): string;
60
61
    /**
62
     * @return string
63
     */
64
    abstract protected static function connectionInstance(): string;
65
66
    /**
67
     * Load override cache configurations
68
     */
69
    protected function loadOverrides()
70
    {
71
        if ($this->overrides === null) {
72
            $this->overrides = [];
73
74
            if ($this->overrideFile !== null) {
75
                $this->overrides = Craft::$app->getConfig()->getConfigFromFile($this->overrideFile);
76
            }
77
        }
78
    }
79
80
    /**
81
     * Returns any configurations from the config file.
82
     *
83
     * @param string $handle
84
     * @return array|null
85
     */
86
    public function getOverrides(string $handle)
87
    {
88
        $this->loadOverrides();
89
        return $this->overrides[$handle] ?? null;
90
    }
91
92
    /**
93
     * @return string
94
     */
95
    protected function getDefaultConnection(): string
96
    {
97
        return static::CONNECTION;
98
    }
99
100
    /**
101
     * @param string $handle
102
     * @throws ConnectionNotFound
103
     */
104
    protected function handleConnectionNotFound(string $handle)
105
    {
106
        throw new ConnectionNotFound(
107
            sprintf(
108
                "Unable to find connection '%s'.",
109
                $handle
110
            )
111
        );
112
    }
113
114
    /**
115
     * @param string $handle
116
     * @param bool $enabledOnly
117
     * @return mixed|null
118
     */
119
    public function find(
120
        string $handle = self::DEFAULT_CONNECTION,
121
        bool $enabledOnly = true
122
    ) {
123
        if ($handle === self::DEFAULT_CONNECTION) {
124
            $handle = $this->getDefaultConnection();
125
        }
126
127
        if (!array_key_exists($handle, $this->connections)) {
128
            $connection = null;
129
            $enabled = false;
130
131
            if ($config = (new Query())
132
                ->select([
133
                    'handle',
134
                    'class',
135
                    'settings',
136
                    'enabled'
137
                ])
138
                ->from(static::tableName())
139
                ->andWhere([
140
                    is_numeric($handle) ? 'id' : 'handle' => $handle
141
                ])
142
                ->one()
143
            ) {
144
                $enabled = (bool)ArrayHelper::remove($config, 'enabled', false);
145
                $connection = $this->create($config);
146
            }
147
            $this->enabled[$handle] = $enabled;
148
            $this->connections[$handle] = $connection;
149
        }
150
151
        // Disabled?
152
        if ($enabledOnly === true && ($this->enabled[$handle] ?? false) === false) {
153
            return null;
154
        }
155
156
        return $this->connections[$handle];
157
    }
158
159
    /**
160
     * @param string $handle
161
     * @param bool $enabledOnly
162
     * @return mixed
163
     * @throws ConnectionNotFound
164
     */
165
    public function get(
166
        string $handle = self::DEFAULT_CONNECTION,
167
        bool $enabledOnly = true
168
    ) {
169
        if (null === ($connection = $this->find($handle, $enabledOnly))) {
170
            return $this->handleConnectionNotFound($handle);
171
        }
172
173
        return $connection;
174
    }
175
176
    /**
177
     * @param $config
178
     * @return mixed|null
179
     */
180
    protected function create(array $config)
181
    {
182
        // Merge settings
183
        $config = ComponentHelper::mergeSettings($config);
184
185
        // Apply overrides
186
        if (null !== ($handle = ArrayHelper::remove($config, 'handle')) &&
187
            null !== ($override = $this->getOverrides($handle))
188
        ) {
189
            $config = array_merge($config, $override);
190
        }
191
192
        try {
193
            $connection = ObjectHelper::create(
194
                $config,
195
                static::connectionInstance()
196
            );
197
        } catch (InvalidConfigurationException $e) {
198
            return null;
199
        }
200
201
        return $connection;
202
    }
203
204
    /**
205
     * @return array
206
     */
207
    public function all(): array
208
    {
209
        $configs = (new Query())
210
            ->select([
211
                'handle',
212
                'class',
213
                'settings',
214
                'enabled'
215
            ])
216
            ->from(static::tableName())
217
            ->all();
218
219
        foreach ($configs as $config) {
220
            $handle = ArrayHelper::getValue($config, 'handle');
221
222
            if (!array_key_exists($handle, $this->connections)) {
223
                $this->enabled[$handle] = (bool)ArrayHelper::remove($config, 'enabled', false);
224
                $this->connections[$handle] = $this->create($config);
225
            }
226
        }
227
228
        return $this->connections;
229
    }
230
}
231