Completed
Push — develop ( 1fc05f...5ee0f5 )
by Nate
11:17
created

Token::upsertInternal()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 6
cp 0
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 12

1 Method

Rating   Name   Duplication   Size   Complexity  
A Token::environmentRecordClass() 0 4 1
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\DateTimeHelper;
13
use craft\validators\DateTimeValidator;
14
use DateTime;
15
use flipbox\ember\helpers\ModelHelper;
16
use flipbox\ember\helpers\QueryHelper;
17
use flipbox\ember\records\ActiveRecordWithId;
18
use flipbox\ember\records\traits\StateAttribute;
19
use flipbox\patron\db\TokenActiveQuery;
20
use yii\db\ActiveQueryInterface;
21
22
/**
23
 * @author Flipbox Factory <[email protected]>
24
 * @since 1.0.0
25
 *
26
 * @property string $accessToken
27
 * @property string $refreshToken
28
 * @property DateTime|null $dateExpires
29
 * @property array $values
30
 * @property ProviderInstance[] $instances
31
 * @property TokenEnvironment[] $environments
32
 */
33
class Token extends ActiveRecordWithId
34
{
35
    use StateAttribute,
36
        traits\ProviderAttribute,
37
        traits\RelatedEnvironmentsAttribute;
38
39
    /**
40
     * The table alias
41
     */
42
    const TABLE_ALIAS = 'patron_tokens';
43
44
    /**
45
     * @inheritdoc
46
     */
47
    protected $getterPriorityAttributes = [
48
        'providerId'
49
    ];
50
51
    /*******************************************
52
     * QUERY
53
     *******************************************/
54
55
    /**
56
     * @inheritdoc
57
     * @return TokenActiveQuery
58
     * @throws \yii\base\InvalidConfigException
59
     */
60
    public static function find()
61
    {
62
        /** @noinspection PhpIncompatibleReturnTypeInspection */
63
        return Craft::createObject(TokenActiveQuery::class, [get_called_class()]);
64
    }
65
66
    /**
67
     * @return bool
68
     */
69
    public function isActive(): bool
70
    {
71
        return $this->isEnabled() && !$this->hasExpired();
72
    }
73
74
    /**
75
     * @return bool
76
     */
77
    public function hasExpired(): bool
78
    {
79
        $dateExpires = $this->dateExpires ?: new DateTime('now');
80
        return DateTimeHelper::isInThePast($dateExpires);
81
    }
82
83
84
    /*******************************************
85
     * EVENTS
86
     *******************************************/
87
88
    /**
89
     * @inheritdoc
90
     */
91
    public function beforeSave($insert): bool
92
    {
93
        if (!parent::beforeSave($insert)) {
94
            return false;
95
        }
96
97
        return $this->beforeSaveEnvironments($insert);
98
    }
99
100
101
    /*******************************************
102
     * UPDATE / INSERT
103
     *******************************************/
104
105
    /**
106
     * @inheritdoc
107
     * @throws \Throwable
108
     */
109
    protected function insertInternal($attributes = null)
110
    {
111
        if (!parent::insertInternal($attributes)) {
112
            return false;
113
        }
114
115
        return $this->insertInternalEnvironments($attributes);
116
    }
117
118
    /**
119
     * @inheritdoc
120
     * @throws \Throwable
121
     */
122
    protected function updateInternal($attributes = null)
123
    {
124
        if (false === ($response = parent::updateInternal($attributes))) {
125
            return false;
126
        }
127
128
        return $this->insertInternalEnvironments($attributes) ? $response : false;
129
    }
130
131
    /*******************************************
132
     * ENVIRONMENTS
133
     *******************************************/
134
135
    /**
136
     * @inheritdoc
137
     */
138
    protected static function environmentRecordClass(): string
139
    {
140
        return TokenEnvironment::class;
141
    }
142
143
    /**
144
     * @inheritdoc
145
     */
146
    protected function prepareEnvironmentRecordConfig(array $config = []): array
147
    {
148
        $config['token'] = $this;
149
        return $config;
150
    }
151
152
    /**
153
     * @inheritdoc
154
     */
155
    protected function environmentRelationshipQuery(): ActiveQueryInterface
156
    {
157
        return $this->hasMany(
158
            static::environmentRecordClass(),
159
            ['tokenId' => 'id']
160
        );
161
    }
162
163
    /**
164
     * @inheritdoc
165
     */
166
    public function rules()
167
    {
168
        return array_merge(
169
            parent::rules(),
170
            $this->stateRules(),
171
            $this->providerRules(),
172
            [
173
                [
174
                    [
175
                        'accessToken',
176
                        'refreshToken'
177
                    ],
178
                    'unique'
179
                ],
180
                [
181
                    [
182
                        'dateExpires'
183
                    ],
184
                    DateTimeValidator::class
185
                ],
186
                [
187
                    [
188
                        'providerId',
189
                        'accessToken'
190
                    ],
191
                    'required'
192
                ],
193
                [
194
                    [
195
                        'accessToken',
196
                        'values',
197
                        'dateExpires'
198
                    ],
199
                    'safe',
200
                    'on' => [
201
                        ModelHelper::SCENARIO_DEFAULT
202
                    ]
203
                ]
204
            ]
205
        );
206
    }
207
208
    /**
209
     * Get all of the associated instances.
210
     *
211
     * @param array $config
212
     * @return \yii\db\ActiveQuery
213
     */
214
    public function getInstances(array $config = [])
215
    {
216
        $query = $this->hasMany(
217
            ProviderInstance::class,
218
            ['providerId' => 'providerId']
219
        );
220
221
        if (!empty($config)) {
222
            QueryHelper::configure(
223
                $query,
224
                $config
225
            );
226
        }
227
228
        return $query;
229
    }
230
}
231