Completed
Push — master ( 19b2ae...0e0de4 )
by Nate
04:43
created

ProviderInstance::createProviderSettings()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 0
cts 15
cp 0
rs 9.456
c 0
b 0
f 0
cc 4
nc 5
nop 0
crap 20
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://flipboxfactory.com/software/patron/license
6
 * @link       https://www.flipboxfactory.com/software/patron/
7
 */
8
9
namespace flipbox\patron\records;
10
11
use Craft;
12
use craft\helpers\ArrayHelper;
13
use craft\helpers\Json;
14
use flipbox\craft\ember\helpers\ModelHelper;
15
use flipbox\craft\ember\helpers\ObjectHelper;
16
use flipbox\craft\ember\records\ActiveRecordWithId;
17
use flipbox\patron\events\RegisterProviderSettings;
18
use flipbox\patron\helpers\ProviderHelper;
19
use flipbox\patron\queries\ProviderInstanceActiveQuery;
20
use flipbox\patron\settings\BaseSettings;
21
use flipbox\patron\settings\SettingsInterface;
22
use flipbox\patron\validators\ProviderSettings as ProviderSettingsValidator;
23
use yii\db\ActiveQueryInterface;
24
25
/**
26
 * @author Flipbox Factory <[email protected]>
27
 * @since 1.0.0
28
 *
29
 * @property string $clientId
30
 * @property string $clientSecret
31
 * @property array $settings
32
 * @property int $providerId
33
 * @property Provider $provider
34
 * @property ProviderEnvironment[] $environments
35
 */
36
class ProviderInstance extends ActiveRecordWithId
37
{
38
    use ProviderAttributeTrait,
39
        RelatedEnvironmentsAttributeTrait;
40
41
    /**
42
     * The table alias
43
     */
44
    const TABLE_ALIAS = 'patron_provider_instances';
45
46
    /**
47
     * The length of the identifier
48
     */
49
    const CLIENT_ID_LENGTH = 100;
50
51
    /**
52
     * The length of the secret
53
     */
54
    const CLIENT_SECRET_LENGTH = 255;
55
56
    /**
57
     * @var SettingsInterface
58
     */
59
    private $providerSettings;
60
61
    /**
62
     * @inheritdoc
63
     */
64
    protected $getterPriorityAttributes = [
65
        'providerId'
66
    ];
67
68
    /**
69
     * @inheritdoc
70
     * @return ProviderInstanceActiveQuery
71
     * @throws \yii\base\InvalidConfigException
72
     */
73
    public static function find()
74
    {
75
        /** @noinspection PhpIncompatibleReturnTypeInspection */
76
        return Craft::createObject(ProviderInstanceActiveQuery::class, [get_called_class()]);
77
    }
78
79
    /**
80
     * @inheritdoc
81
     */
82
    public function rules()
83
    {
84
        return array_merge(
85
            parent::rules(),
86
            $this->providerRules(),
87
            [
88
                [
89
                    [
90
                        'clientId'
91
                    ],
92
                    'string',
93
                    'max' => static::CLIENT_ID_LENGTH
94
                ],
95
                [
96
                    [
97
                        'clientSecret'
98
                    ],
99
                    'string',
100
                    'max' => static::CLIENT_SECRET_LENGTH
101
                ],
102
                [
103
                    [
104
                        'providerId',
105
                        'clientId'
106
                    ],
107
                    'required'
108
                ],
109
                [
110
                    [
111
                        'settings'
112
                    ],
113
                    ProviderSettingsValidator::class
114
                ],
115
                [
116
                    [
117
                        'clientId',
118
                        'clientSecret',
119
                        'settings',
120
                        'environments'
121
                    ],
122
                    'safe',
123
                    'on' => [
124
                        ModelHelper::SCENARIO_DEFAULT
125
                    ]
126
                ]
127
            ]
128
        );
129
    }
130
131
132
    /*******************************************
133
     * EVENTS
134
     *******************************************/
135
136
    /**
137
     * @inheritdoc
138
     */
139
    public function afterFind()
140
    {
141
        if ($this->clientSecret) {
142
            $this->clientSecret = ProviderHelper::decryptClientSecret($this->clientSecret);
143
        }
144
145
        parent::afterFind();
146
    }
147
148
    /**
149
     * @param $insert
150
     * @return bool
151
     * @throws \yii\base\Exception
152
     * @throws \yii\base\InvalidConfigException
153
     */
154
    public function beforeSave($insert)
155
    {
156
        if ($this->clientSecret) {
157
            $this->clientSecret = ProviderHelper::encryptClientSecret($this->clientSecret);
158
        }
159
160
        if (!parent::beforeSave($insert)) {
161
            return false;
162
        }
163
164
        return $this->beforeSaveEnvironments($insert);
165
    }
166
167
    /**
168
     * @inheritdoc
169
     * @throws \Throwable
170
     */
171
    public function afterSave($insert, $changedAttributes)
172
    {
173
        if ($this->clientSecret) {
174
            $this->clientSecret = ProviderHelper::decryptClientSecret($this->clientSecret);
175
        }
176
177
        parent::afterSave($insert, $changedAttributes);
178
    }
179
180
181
    /*******************************************
182
     * UPDATE / INSERT
183
     *******************************************/
184
185
    /**
186
     * @inheritdoc
187
     * @throws \Throwable
188
     */
189
    protected function insertInternal($attributes = null)
190
    {
191
        if (!parent::insertInternal($attributes)) {
192
            return false;
193
        }
194
195
        return $this->insertInternalEnvironments($attributes);
196
    }
197
198
    /**
199
     * @inheritdoc
200
     * @throws \Throwable
201
     */
202
    protected function updateInternal($attributes = null)
203
    {
204
        if (false === ($response = parent::updateInternal($attributes))) {
205
            return false;
206
        }
207
208
        return $this->upsertEnvironmentsInternal($attributes) ? $response : false;
209
    }
210
211
212
    /*******************************************
213
     * ENVIRONMENTS
214
     *******************************************/
215
216
    /**
217
     * @inheritdoc
218
     */
219
    protected static function environmentRecordClass(): string
220
    {
221
        return ProviderEnvironment::class;
222
    }
223
224
    /**
225
     * @inheritdoc
226
     */
227
    protected function prepareEnvironmentRecordConfig(array $config = []): array
228
    {
229
        $config['instance'] = $this;
230
        return $config;
231
    }
232
233
    /**
234
     * @inheritdoc
235
     */
236
    protected function environmentRelationshipQuery(): ActiveQueryInterface
237
    {
238
        return $this->hasMany(
239
            static::environmentRecordClass(),
240
            ['instanceId' => 'id']
241
        );
242
    }
243
244
    /**
245
     * @return SettingsInterface
246
     * @throws \yii\base\InvalidConfigException
247
     */
248
    public function getProviderSettings(): SettingsInterface
249
    {
250
        if (!$this->providerSettings instanceof SettingsInterface) {
251
            $this->providerSettings = $this->createProviderSettings();
252
        }
253
254
        return $this->providerSettings;
255
    }
256
257
    /**
258
     * @return SettingsInterface
259
     * @throws \yii\base\InvalidConfigException
260
     */
261
    protected function createProviderSettings(): SettingsInterface
262
    {
263
        if (null === ($provider = $this->getProvider())) {
264
            return new BaseSettings();
265
        }
266
267
        $event = new RegisterProviderSettings();
268
269
        RegisterProviderSettings::trigger(
270
            $provider->class,
271
            RegisterProviderSettings::REGISTER_SETTINGS,
272
            $event
273
        );
274
275
        $settings = $this->settings;
276
277
        if (is_string($settings)) {
278
            $settings = Json::decodeIfJson($settings);
279
        }
280
281
        if (!is_array($settings)) {
282
            $settings = ArrayHelper::toArray($settings, [], true);
283
        }
284
285
        $settings['class'] = $event->class;
286
287
        /** @noinspection PhpIncompatibleReturnTypeInspection */
288
        return ObjectHelper::create($settings, SettingsInterface::class);
289
    }
290
}
291