Completed
Push — develop ( e45dbf...2d4657 )
by Nate
04:34
created

Provider::getEnvironments()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 0
cts 14
cp 0
rs 9.7333
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 6
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\Template;
13
use flipbox\ember\helpers\ModelHelper;
14
use flipbox\ember\helpers\ObjectHelper;
15
use flipbox\ember\helpers\QueryHelper;
16
use flipbox\ember\records\ActiveRecordWithId;
17
use flipbox\ember\records\traits\StateAttribute;
18
use flipbox\ember\traits\HandleRules;
19
use flipbox\patron\db\ProviderActiveQuery;
20
use flipbox\patron\helpers\ProviderHelper;
21
use flipbox\patron\Patron;
22
use flipbox\patron\providers\SettingsInterface;
23
use flipbox\patron\validators\ProviderValidator;
24
use Twig_Markup;
25
26
/**
27
 * @author Flipbox Factory <[email protected]>
28
 * @since 1.0.0
29
 *
30
 * @property string $clientId
31
 * @property string $clientSecret
32
 * @property string $class
33
 * @property array $settings
34
 * @property Token[] tokens
35
 * @property ProviderEnvironment[] $environments
36
 */
37
class Provider extends ActiveRecordWithId
38
{
39
    use HandleRules,
40
        StateAttribute;
41
42
    /**
43
     * The table alias
44
     */
45
    const TABLE_ALIAS = 'patron_providers';
46
47
    /**
48
     * @var SettingsInterface
49
     */
50
    private $settingsModel;
51
52
    /**
53
     * The length of the identifier
54
     */
55
    const CLIENT_ID_LENGTH = 100;
56
57
    /**
58
     * The length of the secret
59
     */
60
    const CLIENT_SECRET_LENGTH = 100;
61
62
    /**
63
     * @inheritdoc
64
     * @return ProviderActiveQuery
65
     * @throws \yii\base\InvalidConfigException
66
     */
67
    public static function find()
68
    {
69
        /** @noinspection PhpIncompatibleReturnTypeInspection */
70
        return Craft::createObject(ProviderActiveQuery::class, [get_called_class()]);
71
    }
72
73
    /**
74
     * @inheritdoc
75
     */
76
    public function rules()
77
    {
78
        return array_merge(
79
            parent::rules(),
80
            $this->handleRules(),
81
            $this->stateRules(),
82
            [
83
                [
84
                    [
85
                        'clientId'
86
                    ],
87
                    'string',
88
                    'max' => static::CLIENT_ID_LENGTH
89
                ],
90
                [
91
                    [
92
                        'clientSecret'
93
                    ],
94
                    'string',
95
                    'max' => static::CLIENT_SECRET_LENGTH
96
                ],
97
                [
98
                    [
99
                        'class'
100
                    ],
101
                    ProviderValidator::class
102
                ],
103
                [
104
                    [
105
                        'clientId',
106
                        'class'
107
                    ],
108
                    'required'
109
                ],
110
                [
111
                    [
112
                        'clientId',
113
                        'clientSecret',
114
                        'class',
115
                        'settings'
116
                    ],
117
                    'safe',
118
                    'on' => [
119
                        ModelHelper::SCENARIO_DEFAULT
120
                    ]
121
                ]
122
            ]
123
        );
124
    }
125
126
    /**
127
     * Get all of the associated tokens.
128
     *
129
     * @param array $config
130
     * @return \yii\db\ActiveQuery
131
     */
132
    public function getTokens(array $config = [])
133
    {
134
        $query = $this->hasMany(
135
            Token::class,
136
            ['providerId' => 'id']
137
        );
138
139
        if (!empty($config)) {
140
            QueryHelper::configure(
141
                $query,
142
                $config
143
            );
144
        }
145
146
        return $query;
147
    }
148
149
    /**
150
     * Get all of the associated environments.
151
     *
152
     * @param array $config
153
     * @return \yii\db\ActiveQuery
154
     */
155
    public function getEnvironments(array $config = [])
156
    {
157
        $query = $this->hasMany(
158
            ProviderEnvironment::class,
159
            ['providerId' => 'id']
160
        )->indexBy('environment');
161
162
        if (!empty($config)) {
163
            QueryHelper::configure(
164
                $query,
165
                $config
166
            );
167
        }
168
169
        return $query;
170
    }
171
172
    /**
173
     * @param array $environments
174
     * @return $this
175
     */
176
    public function setEnvironments(array $environments = [])
177
    {
178
        $records = [];
179
        foreach (array_filter($environments) as $key => $environment) {
180
            $records[] = $this->resolveEnvironment($key, $environment);
181
        }
182
183
        $this->populateRelation('environments', $records);
184
        return $this;
185
    }
186
187
    /**
188
     * @param string $key
189
     * @param $environment
190
     * @return ProviderEnvironment
191
     */
192
    protected function resolveEnvironment(string $key, $environment): ProviderEnvironment
193
    {
194
        if (!$record = $this->environments[$key] ?? null) {
195
            $record = new ProviderEnvironment();
196
        }
197
198
        if (!is_array($environment)) {
199
            $environment = ['environment' => $environment];
200
        }
201
202
        /** @noinspection PhpIncompatibleReturnTypeInspection */
203
        return ObjectHelper::populate(
204
            $record,
205
            $environment
206
        );
207
    }
208
209
    /*******************************************
210
     * EVENTS
211
     *******************************************/
212
213
214
    /**
215
     * @inheritdoc
216
     * @throws \Throwable
217
     */
218
    public function afterSave($insert, $changedAttributes)
219
    {
220
        Patron::getInstance()->manageProviders()->saveEnvironments($this);
221
        parent::afterSave($insert, $changedAttributes);
222
    }
223
224
    /**
225
     * @return string
226
     */
227
    public function getDisplayName(): string
228
    {
229
        return ProviderHelper::displayName(
230
            $this->class
231
        );
232
    }
233
234
    /**
235
     * @return Twig_Markup
236
     * @throws \yii\base\InvalidConfigException
237
     */
238
    public function getSettingsHtml(): Twig_Markup
239
    {
240
        return Template::raw(
241
            $this->getSettingsModel()->inputHtml()
242
        );
243
    }
244
245
    /**
246
     * @return SettingsInterface
247
     * @throws \yii\base\InvalidConfigException
248
     */
249
    protected function getSettingsModel(): SettingsInterface
250
    {
251
        if (!$this->settingsModel instanceof SettingsInterface) {
252
            $this->settingsModel = Patron::getInstance()->manageProviders()->resolveSettings($this, $this->settings);
253
        }
254
255
        return $this->settingsModel;
256
    }
257
}
258