Completed
Push — master ( e45dbf...3a73d5 )
by Nate
05:43 queued 04:08
created

ManageTokens::saveEnvironments()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 34
ccs 0
cts 18
cp 0
rs 9.0648
c 0
b 0
f 0
cc 5
nc 8
nop 1
crap 30
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\services;
10
11
use Craft;
12
use flipbox\ember\helpers\ArrayHelper;
13
use flipbox\ember\services\traits\records\Accessor;
14
use flipbox\patron\db\TokenQuery;
15
use flipbox\patron\Patron;
16
use flipbox\patron\records\Token;
17
use flipbox\patron\records\TokenEnvironment;
18
use League\OAuth2\Client\Provider\AbstractProvider;
19
use League\OAuth2\Client\Token\AccessToken;
20
use yii\base\Component;
21
22
/**
23
 * @author Flipbox Factory <[email protected]>
24
 * @since 1.0.0
25
 *
26
 * @method Token create(array $attributes = [])
27
 * @method TokenQuery getQuery($config = [])
28
 * @method Token parentFind($identifier)
29
 * @method Token get($identifier)
30
 * @method Token findByCondition($condition = [])
31
 * @method Token getByCondition($condition = [])
32
 * @method Token findByCriteria($criteria = [])
33
 * @method Token getByCriteria($criteria = [])
34
 * @method Token[] findAllByCondition($condition = [])
35
 * @method Token[] getAllByCondition($condition = [])
36
 * @method Token[] findAllByCriteria($criteria = [])
37
 * @method Token[] getAllByCriteria($criteria = [])
38
 */
39
class ManageTokens extends Component
40
{
41
    use Accessor {
42
        find as parentFind;
43
    }
44
45
    /**
46
     * @inheritdoc
47
     */
48
    public static function recordClass(): string
49
    {
50
        return Token::class;
51
    }
52
53
    /**
54
     * @param array $config
55
     * @return array
56
     */
57
    protected function prepareQueryConfig($config = [])
58
    {
59
        if (!is_array($config)) {
60
            $config = ArrayHelper::toArray($config, [], true);
61
        }
62
63
        // Allow disabled when managing
64
        if (!array_key_exists('enabled', $config)) {
65
            $config['enabled'] = null;
66
        }
67
68
        // Allow all environments when managing
69
        if (!array_key_exists('environment', $config)) {
70
            $config['environment'] = null;
71
        }
72
73
        return $config;
74
    }
75
76
    /**
77
     * @inheritdoc
78
     */
79
    public function find($identifier)
80
    {
81
        if ($identifier instanceof AccessToken) {
82
            return $this->findByAccessToken($identifier);
83
        }
84
85
        if ($identifier instanceof AbstractProvider) {
86
            return $this->findByProvider($identifier);
87
        }
88
89
        return $this->parentFind($identifier);
90
    }
91
92
    /*******************************************
93
     * FIND/GET BY ACCESS TOKEN
94
     *******************************************/
95
96
    /**
97
     * @param AccessToken $accessToken
98
     * @return Token|null
99
     */
100
    public function findByAccessToken(AccessToken $accessToken)
101
    {
102
        return $this->findByCriteria(['accessToken' => $accessToken->getToken()]);
103
    }
104
105
    /*******************************************
106
     * FIND/GET BY PROVIDER
107
     *******************************************/
108
109
    /**
110
     * @param AbstractProvider $provider
111
     * @return Token|null
112
     */
113
    public function findByProvider(AbstractProvider $provider)
114
    {
115
        if (null === ($providerId = Patron::getInstance()->getProviders()->getId($provider))) {
116
            return null;
117
        }
118
119
        return $this->findByCriteria(['providerId' => $providerId]);
120
    }
121
122
    /*******************************************
123
     * ENVIRONMENTS
124
     *******************************************/
125
126
    /**
127
     * @param Token $token
128
     * @return bool
129
     * @throws \Throwable
130
     * @throws \yii\db\StaleObjectException
131
     */
132
    public function saveEnvironments(Token $token)
133
    {
134
        $successful = true;
135
136
        /** @var TokenEnvironment[] $allRecords */
137
        $allRecords = $token->getEnvironments()
138
            ->all();
139
140
        foreach ($this->resolveEnvironments($token) as $model) {
141
            ArrayHelper::remove($allRecords, $model->environment);
142
            $model->tokenId = $token->getId();
143
144
            if (!$model->save()) {
145
                $successful = false;
146
                // Log the errors
147
                $error = Craft::t(
148
                    'patron',
149
                    "Couldn't save environment due to validation errors:"
150
                );
151
                foreach ($model->getFirstErrors() as $attributeError) {
152
                    $error .= "\n- " . Craft::t('patron', $attributeError);
153
                }
154
155
                $token->addError('sites', $error);
156
            }
157
        }
158
159
        // Delete old records
160
        foreach ($allRecords as $record) {
161
            $record->delete();
162
        }
163
164
        return $successful;
165
    }
166
167
    /**
168
     * @param Token $token
169
     * @return TokenEnvironment[]
170
     */
171
    protected function defaultEnvironments(Token $token): array
172
    {
173
        $environments = [];
174
175
        foreach (Patron::getInstance()->getSettings()->getDefaultEnvironments() as $environment) {
176
            $environments[$environment] = new TokenEnvironment([
177
                'tokenId' => $token->getId(),
178
                'environment' => $environment
179
            ]);
180
        }
181
182
        return $environments;
183
    }
184
185
    /**
186
     * @param Token $token
187
     * @return array
188
     */
189
    protected function resolveEnvironments(Token $token): array
190
    {
191
        $environments = $token->environments;
192
193
        if (empty($environments)) {
194
            $environments = $this->defaultEnvironments($token);
195
        }
196
197
        return $environments;
198
    }
199
200
    /*******************************************
201
     * STATES
202
     *******************************************/
203
204
    /**
205
     * @param Token $record
206
     * @return bool
207
     */
208
    public function disable(Token $record)
209
    {
210
        $record->enabled = false;
211
        return $record->save(true, ['enabled']);
212
    }
213
214
    /**
215
     * @param Token $model
216
     * @return bool
217
     */
218
    public function enable(Token $model)
219
    {
220
        $model->enabled = true;
221
        return $model->save(true, ['enabled']);
222
    }
223
}
224