Completed
Push — master ( 04ac75...81967b )
by Nate
17:06
created

Token::resolveEnvironment()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 0
cts 13
cp 0
rs 9.7333
c 0
b 0
f 0
cc 3
nc 4
nop 2
crap 12
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
     * @inheritdoc
68
     */
69
    public function rules()
70
    {
71
        return array_merge(
72
            parent::rules(),
73
            $this->stateRules(),
74
            $this->providerRules(),
75
            [
76
                [
77
                    [
78
                        'accessToken',
79
                        'refreshToken'
80
                    ],
81
                    'unique'
82
                ],
83
                [
84
                    [
85
                        'dateExpires'
86
                    ],
87
                    DateTimeValidator::class
88
                ],
89
                [
90
                    [
91
                        'providerId',
92
                        'accessToken'
93
                    ],
94
                    'required'
95
                ],
96
                [
97
                    [
98
                        'accessToken',
99
                        'values',
100
                        'dateExpires'
101
                    ],
102
                    'safe',
103
                    'on' => [
104
                        ModelHelper::SCENARIO_DEFAULT
105
                    ]
106
                ]
107
            ]
108
        );
109
    }
110
111
    /**
112
     * @return bool
113
     */
114
    public function isActive(): bool
115
    {
116
        return $this->isEnabled() && !$this->hasExpired();
117
    }
118
119
    /**
120
     * @return bool
121
     */
122
    public function hasExpired(): bool
123
    {
124
        $dateExpires = $this->dateExpires ?: new DateTime('now');
125
        return DateTimeHelper::isInThePast($dateExpires);
126
    }
127
128
129
    /*******************************************
130
     * EVENTS
131
     *******************************************/
132
133
    /**
134
     * @inheritdoc
135
     */
136
    public function beforeSave($insert): bool
137
    {
138
        if (!parent::beforeSave($insert)) {
139
            return false;
140
        }
141
142
        return $this->beforeSaveEnvironments($insert);
143
    }
144
145
146
    /*******************************************
147
     * UPDATE / INSERT
148
     *******************************************/
149
150
    /**
151
     * @inheritdoc
152
     * @throws \Throwable
153
     */
154
    protected function insertInternal($attributes = null)
155
    {
156
        if (!parent::insertInternal($attributes)) {
157
            return false;
158
        }
159
160
        return $this->insertInternalEnvironments($attributes);
161
    }
162
163
    /**
164
     * @inheritdoc
165
     * @throws \Throwable
166
     */
167
    protected function updateInternal($attributes = null)
168
    {
169
        if (false === ($response = parent::updateInternal($attributes))) {
170
            return false;
171
        }
172
173
        return $this->upsertEnvironmentsInternal($attributes) ? $response : false;
174
    }
175
176
    /*******************************************
177
     * ENVIRONMENTS
178
     *******************************************/
179
180
    /**
181
     * @inheritdoc
182
     */
183
    protected static function environmentRecordClass(): string
184
    {
185
        return TokenEnvironment::class;
186
    }
187
188
    /**
189
     * @inheritdoc
190
     */
191
    protected function prepareEnvironmentRecordConfig(array $config = []): array
192
    {
193
        $config['token'] = $this;
194
        return $config;
195
    }
196
197
    /**
198
     * @inheritdoc
199
     */
200
    protected function environmentRelationshipQuery(): ActiveQueryInterface
201
    {
202
        return $this->hasMany(
203
            static::environmentRecordClass(),
204
            ['tokenId' => 'id']
205
        );
206
    }
207
208
209
    /**
210
     * Get all of the associated provider instances.
211
     *
212
     * @param array $config
213
     * @return \yii\db\ActiveQuery
214
     */
215
    public function getInstances(array $config = [])
216
    {
217
        $query = $this->hasMany(
218
            ProviderInstance::class,
219
            ['providerId' => 'providerId']
220
        );
221
222
        if (!empty($config)) {
223
            QueryHelper::configure(
224
                $query,
225
                $config
226
            );
227
        }
228
229
        return $query;
230
    }
231
}
232