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

ManageTokens::saveEnvironments()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 37

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 37
ccs 0
cts 21
cp 0
rs 9.0168
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[] $allProviders */
137
        $allProviders = $token->hasMany(
138
            TokenEnvironment::class,
139
            ['providerId' => 'id']
140
        )->indexBy('environment')
141
            ->all();
142
143
        foreach ($token->environments as $model) {
144
            ArrayHelper::remove($allProviders, $model->environment);
145
            $model->providerId = $token->getId();
0 ignored issues
show
Documentation introduced by
The property providerId does not exist on object<flipbox\patron\records\TokenEnvironment>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
146
147
            if (!$model->save()) {
148
                $successful = false;
149
                // Log the errors
150
                $error = Craft::t(
151
                    'patron',
152
                    "Couldn't save environment due to validation errors:"
153
                );
154
                foreach ($model->getFirstErrors() as $attributeError) {
155
                    $error .= "\n- " . Craft::t('patron', $attributeError);
156
                }
157
158
                $token->addError('sites', $error);
159
            }
160
        }
161
162
        // Delete old records
163
        foreach ($allProviders as $settings) {
164
            $settings->delete();
165
        }
166
167
        return $successful;
168
    }
169
170
    /*******************************************
171
     * STATES
172
     *******************************************/
173
174
    /**
175
     * @param Token $record
176
     * @return bool
177
     */
178
    public function disable(Token $record)
179
    {
180
        $record->enabled = false;
181
        return $record->save(true, ['enabled']);
182
    }
183
184
    /**
185
     * @param Token $model
186
     * @return bool
187
     */
188
    public function enable(Token $model)
189
    {
190
        $model->enabled = true;
191
        return $model->save(true, ['enabled']);
192
    }
193
}
194