Passed
Push — master ( 531ae6...ffc6fc )
by Rutger
13:24
created

Oauth2Client::getTermsOfServiceUri()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace rhertogh\Yii2Oauth2Server\models;
4
5
use rhertogh\Yii2Oauth2Server\helpers\DiHelper;
6
use rhertogh\Yii2Oauth2Server\interfaces\models\Oauth2ClientInterface;
7
use rhertogh\Yii2Oauth2Server\interfaces\models\Oauth2ClientScopeInterface;
8
use rhertogh\Yii2Oauth2Server\interfaces\models\Oauth2ScopeInterface;
9
use rhertogh\Yii2Oauth2Server\models\behaviors\DateTimeBehavior;
10
use rhertogh\Yii2Oauth2Server\models\traits\Oauth2EnabledTrait;
11
use rhertogh\Yii2Oauth2Server\models\traits\Oauth2EntityIdentifierTrait;
12
use rhertogh\Yii2Oauth2Server\Oauth2Module;
13
use Yii;
14
use yii\base\Exception;
15
use yii\base\InvalidArgumentException;
16
use yii\base\InvalidConfigException;
17
use yii\base\UnknownPropertyException;
18
use yii\helpers\ArrayHelper;
19
use yii\helpers\Json;
20
21
class Oauth2Client extends base\Oauth2Client implements Oauth2ClientInterface
22
{
23
    use Oauth2EntityIdentifierTrait;
24
    use Oauth2EnabledTrait;
25
26
    protected const ENCRYPTED_ATTRIBUTES = ['secret', 'old_secret'];
27
28
    /**
29
     * Minimum lenght for client secret.
30
     * @var int
31
     */
32
    public $minimumSecretLenth = 10;
33
34
    /////////////////////////////
35
    /// ActiveRecord Settings ///
36
    /////////////////////////////
37
38
    /**
39
     * @inheritDoc
40
     */
41 60
    public function behaviors()
42
    {
43 60
        return ArrayHelper::merge(parent::behaviors(), [
44 60
            'dateTimeBehavior' => DateTimeBehavior::class
45 60
        ]);
46
    }
47
48
    /**
49
     * @inheritDoc
50
     */
51 1
    public function rules()
52
    {
53 1
        return ArrayHelper::merge(parent::rules(), [
54 1
            [
55 1
                ['secret'],
56 1
                'required',
57 1
                'when' => fn(self $model) => $model->isConfidential(),
58 1
            ],
59 1
            [
60 1
                ['scope_access'],
61 1
                'in',
62 1
                'range' => static::SCOPE_ACCESSES,
63 1
            ]
64 1
        ]);
65
    }
66
67
    /////////////////////////
68
    /// Getters & Setters ///
69
    /////////////////////////
70
71
    /**
72
     * @inheritdoc
73
     */
74 61
    public function __set($name, $value)
75
    {
76 61
        if ($name === 'secret') { // Don't allow setting the secret via magic method.
77 1
            throw new UnknownPropertyException('For security the "secret" property must be set via setSecret()');
78
        } else {
79 60
            parent::__set($name, $value);
80
        }
81
    }
82
83
    /**
84
     * @inheritdoc
85
     */
86 4
    public function getName()
87
    {
88 4
        return $this->name;
89
    }
90
91
    /**
92
     * @inheritdoc
93
     */
94 1
    public function setName($name)
95
    {
96 1
        $this->name = $name;
97 1
        return $this;
98
    }
99
100
    /**
101
     * @inheritdoc
102
     */
103 1
    public function getType()
104
    {
105 1
        return $this->type;
106
    }
107
108
    /**
109
     * @inheritdoc
110
     */
111 2
    public function setType($type)
112
    {
113 2
        if (!in_array($type, Oauth2ClientInterface::TYPES)) {
114 1
            throw new InvalidArgumentException('Unknown type "' . $type . '".');
115
        }
116
117 1
        $this->type = $type;
118 1
        return $this;
119
    }
120
121
    /**
122
     * @inheritdoc
123
     * @throws InvalidConfigException
124
     */
125 9
    public function getRedirectUri()
126
    {
127 9
        $uris = $this->redirect_uris;
128 9
        if (empty($uris)) {
129 1
            return [];
130
        }
131
132 8
        if (is_string($uris)) {
0 ignored issues
show
introduced by
The condition is_string($uris) is always false.
Loading history...
133
            try {
134 5
                $uris = Json::decode($uris);
135 1
            } catch (InvalidArgumentException $e) {
136 1
                throw new InvalidConfigException('Invalid json in redirect_uris for client ' . $this->id, 0, $e);
137
            }
138
        }
139
140 7
        if (is_string($uris)) {
0 ignored issues
show
introduced by
The condition is_string($uris) is always false.
Loading history...
141 1
            $uris = [$uris];
142 6
        } elseif (is_array($uris)) {
0 ignored issues
show
introduced by
The condition is_array($uris) is always true.
Loading history...
143 5
            $uris = array_values($uris);
144
        } else {
145 1
            throw new InvalidConfigException('`redirect_uris` must be a JSON encoded string or array of strings.');
146
        }
147
148 6
        foreach ($uris as $key => $uri) {
149 6
            if (!is_string($uri)) {
150 1
                throw new InvalidConfigException('`redirect_uris` must be a JSON encoded string or array of strings.');
151
            }
152 5
            preg_match_all('/\${(?<name>[a-zA-Z0-9_]+)}/', $uri, $matches, PREG_SET_ORDER);
153 5
            foreach ($matches as $match) {
154 1
                $envVar = getenv($match['name']);
155 1
                if (strlen($envVar)) {
156 1
                    $uris[$key] = str_replace($match[0], $envVar, $uris[$key]);
157
                } else {
158 1
                    unset($uris[$key]);
159 1
                    break;
160
                }
161
            }
162
        }
163 5
        return array_values($uris); // Re-index array in case elements were removed.
164
    }
165
166
    /**
167
     * @inheritDoc
168
     */
169 4
    public function setRedirectUri($uri)
170
    {
171 4
        if (is_array($uri)) {
172 2
            foreach ($uri as $value) {
173 2
                if (!is_string($value)) {
174 1
                    throw new InvalidArgumentException('When $uri is an array, its values must be strings.');
175
                }
176
            }
177 1
            $uri = Json::encode($uri);
178 2
        } elseif (is_string($uri)) {
179 1
            $uri = Json::encode([$uri]);
180
        } else {
181 1
            throw new InvalidArgumentException('$uri must be a string or an array, got: ' . gettype($uri));
182
        }
183
184 2
        $this->redirect_uris = $uri;
0 ignored issues
show
Documentation Bug introduced by
It seems like $uri of type string is incompatible with the declared type array of property $redirect_uris.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
185
    }
186
187 2
    public function isVariableRedirectUriQueryAllowed()
188
    {
189 2
        return (bool)$this->allow_variable_redirect_uri_query;
190
    }
191 1
    public function setAllowVariableRedirectUriQuery($allowVariableRedirectUriQuery)
192
    {
193 1
        $this->allow_variable_redirect_uri_query = $allowVariableRedirectUriQuery;
194 1
        return $this;
195
    }
196
197
    /**
198
     * @inheritDoc
199
     */
200 4
    public function getUserAccountSelection()
201
    {
202 4
        return $this->user_account_selection;
203
    }
204
205 4
    public function endUsersMayAuthorizeClient()
206
    {
207 4
        return $this->end_users_may_authorize_client;
208
    }
209
210 1
    public function setEndUsersMayAuthorizeClient($endUsersMayAuthorizeClient)
211
    {
212 1
        $this->end_users_may_authorize_client = $endUsersMayAuthorizeClient;
213 1
        return $this;
214
    }
215
216
    /**
217
     * @inheritDoc
218
     */
219 1
    public function setUserAccountSelection($userAccountSelectionConfig)
220
    {
221 1
        $this->user_account_selection = $userAccountSelectionConfig;
222 1
        return $this;
223
    }
224
225
    /**
226
     * @inheritDoc
227
     */
228 4
    public function isAuthCodeWithoutPkceAllowed()
229
    {
230 4
        return (bool)$this->allow_auth_code_without_pkce;
231
    }
232
233
    /**
234
     * @inheritDoc
235
     */
236 1
    public function setAllowAuthCodeWithoutPkce($allowAuthCodeWithoutPkce)
237
    {
238 1
        $this->allow_auth_code_without_pkce = $allowAuthCodeWithoutPkce;
239 1
        return $this;
240
    }
241
242
    /**
243
     * @inheritDoc
244
     */
245 2
    public function skipAuthorizationIfScopeIsAllowed()
246
    {
247 2
        return (bool)$this->skip_authorization_if_scope_is_allowed;
248
    }
249
250
    /**
251
     * @inheritDoc
252
     */
253 1
    public function setSkipAuthorizationIfScopeIsAllowed($skipAuthIfScopeIsAllowed)
254
    {
255 1
        $this->skip_authorization_if_scope_is_allowed = $skipAuthIfScopeIsAllowed;
256 1
        return $this;
257
    }
258
259
    /**
260
     * @inheritDoc
261
     */
262 1
    public function getClientCredentialsGrantUserId()
263
    {
264 1
        return $this->client_credentials_grant_user_id;
265
    }
266
267
    /**
268
     * @inheritDoc
269
     */
270 1
    public function setClientCredentialsGrantUserId($userId)
271
    {
272 1
        $this->client_credentials_grant_user_id = $userId;
273 1
        return $this;
274
    }
275
276
    /**
277
     * @inheritDoc
278
     */
279 1
    public function getOpenIdConnectAllowOfflineAccessWithoutConsent()
280
    {
281 1
        return (bool)$this->oidc_allow_offline_access_without_consent;
282
    }
283
284
    /**
285
     * @inheritDoc
286
     */
287 1
    public function setOpenIdConnectAllowOfflineAccessWithoutConsent($allowOfflineAccessWithoutConsent)
288
    {
289 1
        $this->oidc_allow_offline_access_without_consent = $allowOfflineAccessWithoutConsent;
290 1
        return $this;
291
    }
292
293
    /**
294
     * @inheritDoc
295
     */
296 1
    public function getOpenIdConnectUserinfoEncryptedResponseAlg()
297
    {
298 1
        return $this->oidc_userinfo_encrypted_response_alg;
299
    }
300
301
    /**
302
     * @inheritDoc
303
     */
304 1
    public function setOpenIdConnectUserinfoEncryptedResponseAlg($algorithm)
305
    {
306 1
        $this->oidc_userinfo_encrypted_response_alg = $algorithm;
307 1
        return $this;
308
    }
309
310
    /**
311
     * @inheritdoc
312
     */
313 9
    public function isConfidential()
314
    {
315 9
        return (int)$this->type !== static::TYPE_PUBLIC;
316
    }
317
318
    /**
319
     * @inheritDoc
320
     */
321 19
    public function getScopeAccess()
322
    {
323 19
        return (int)$this->scope_access;
324
    }
325
326
    /**
327
     * @inheritDoc
328
     */
329 2
    public function setScopeAccess($scopeAccess)
330
    {
331 2
        if (!in_array($scopeAccess, Oauth2ClientInterface::SCOPE_ACCESSES)) {
332 1
            throw new InvalidArgumentException('Unknown scope access "' . $scopeAccess . '".');
333
        }
334
335 1
        $this->scope_access = $scopeAccess;
336 1
        return $this;
337
    }
338
339
    /**
340
     * @inheritDoc
341
     */
342 3
    public static function getEncryptedAttributes()
343
    {
344 3
        return static::ENCRYPTED_ATTRIBUTES;
345
    }
346
347
    /**
348
     * @inheritDoc
349
     */
350 2
    public static function rotateStorageEncryptionKeys($encryptor, $newKeyName = null)
351
    {
352 2
        $numUpdated = 0;
353 2
        $encryptedAttributes = static::getEncryptedAttributes();
354 2
        $query = static::find()->andWhere(['NOT', array_fill_keys($encryptedAttributes, null)]);
355
356 2
        $transaction = static::getDb()->beginTransaction();
357
        try {
358
            /** @var static $client */
359 2
            foreach ($query->each() as $client) {
360 2
                $client->rotateStorageEncryptionKey($encryptor, $newKeyName);
361 2
                if ($client->getDirtyAttributes($encryptedAttributes)) {
362 2
                    $client->persist();
363 1
                    $numUpdated++;
364
                }
365
            }
366 1
            $transaction->commit();
367 1
        } catch (\Exception $e) {
368 1
            $transaction->rollBack();
369 1
            throw $e;
370
        }
371
372 1
        return $numUpdated;
373
    }
374
375
    /**
376
     * @inheritDoc
377
     */
378
    public static function getUsedStorageEncryptionKeys($encryptor)
379
    {
380
        $encryptedAttributes = static::getEncryptedAttributes();
381
        $query = static::find()->andWhere(['NOT', array_fill_keys($encryptedAttributes, null)]);
382
383
        $keyUsage = [];
384
        foreach ($query->each() as $client) {
385
            foreach ($encryptedAttributes as $encryptedAttribute) {
386
                $data = $client->$encryptedAttribute;
387
                if (!empty($data)) {
388
                    ['keyName' => $keyName] = $encryptor->parseData($data);
389
                    if (array_key_exists($keyName, $keyUsage)) {
390
                        $keyUsage[$keyName][] = $client->getPrimaryKey();
391
                    } else {
392
                        $keyUsage[$keyName] = [$client->getPrimaryKey()];
393
                    }
394
                }
395
            }
396
        }
397
398
        return $keyUsage;
399
    }
400
401
    /**
402
     * @inheritDoc
403
     */
404 3
    public function rotateStorageEncryptionKey($encryptor, $newKeyName = null)
405
    {
406 3
        foreach (static::getEncryptedAttributes() as $attribute) {
407 3
            $data = $this->getAttribute($attribute);
408 3
            if ($data) {
409
                try {
410 3
                    $this->setAttribute($attribute, $encryptor->rotateKey($data, $newKeyName));
411
                } catch (\Exception $e) {
412
                    throw new Exception('Unable to rotate key for client "' . $this->identifier
413
                        . '", attribute "' . $attribute . '": ' . $e->getMessage(), 0, $e);
414
                }
415
            }
416
        }
417
    }
418
419
    /**
420
     * @inheritDoc
421
     */
422 4
    public function setSecret($secret, $encryptor, $oldSecretValidUntil = null, $keyName = null)
423
    {
424 4
        if ($this->isConfidential()) {
425 4
            if (!$this->validateNewSecret($secret, $error)) {
426 1
                throw new InvalidArgumentException($error);
427
            }
428
429
            // Ensure we clear out any old secret.
430 3
            $this->setAttribute('old_secret', null);
431 3
            $this->setAttribute('old_secret_valid_until', null);
432
433 3
            if ($oldSecretValidUntil) {
434 1
                $oldSecretData = $this->getAttribute('secret') ?? null;
435 1
                if ($oldSecretData) {
436
                    // Ensure correct encryption key.
437 1
                    $oldSecretData = $encryptor->encryp($encryptor->decrypt($oldSecretData), $keyName);
438 1
                    $this->setAttribute('old_secret', $oldSecretData);
439
440 1
                    if ($oldSecretValidUntil instanceof \DateInterval) {
441 1
                        $oldSecretValidUntil = (new \DateTimeImmutable())->add($oldSecretValidUntil);
442
                    }
443 1
                    $this->setAttribute('old_secret_valid_until', $oldSecretValidUntil);
444
                }
445
            }
446
447 3
            $this->setAttribute('secret', $encryptor->encryp($secret, $keyName));
448
        } else {
449 1
            if ($secret !== null) {
450 1
                throw new InvalidArgumentException(
451 1
                    'The secret for a non-confidential client can only be set to `null`.'
452 1
                );
453
            }
454
455 1
            $this->setAttribute('secret', null);
456
        }
457
    }
458
459
    /**
460
     * @inheritDoc
461
     */
462 4
    public function validateNewSecret($secret, &$error)
463
    {
464 4
        $error = null;
465 4
        if (mb_strlen($secret) < $this->minimumSecretLenth) {
466 1
            $error = 'Secret should be at least ' . $this->minimumSecretLenth . ' characters.';
467
        }
468
469 4
        return $error === null;
470
    }
471
472
    /**
473
     * @inheritDoc
474
     */
475 2
    public function getDecryptedSecret($encryptor)
476
    {
477 2
        return $encryptor->decrypt($this->secret);
478
    }
479
480
    /**
481
     * @inheritDoc
482
     */
483
    public function getDecryptedOldSecret($encryptor)
484
    {
485
        return $encryptor->decrypt($this->old_secret);
486
    }
487
488
    /**
489
     * @inheritDoc
490
     */
491
    public function getOldSecretValidUntil()
492
    {
493
        return $this->old_secret_valid_until;
494
    }
495
496
    /**
497
     * @inheritdoc
498
     */
499 1
    public function validateSecret($secret, $encryptor)
500
    {
501 1
        return is_string($secret)
502 1
            && strlen($secret)
503 1
            && (
504 1
                Yii::$app->security->compareString($this->getDecryptedSecret($encryptor), $secret)
505 1
                || (
506 1
                    !empty($this->old_secret)
507 1
                    && !empty($this->old_secret_valid_until)
508 1
                    && $this->old_secret_valid_until > (new \DateTime())
509 1
                    && Yii::$app->security->compareString($encryptor->decrypt($this->old_secret), $secret)
510 1
                )
511 1
            );
512
    }
513
514
    /**
515
     * @inheritdoc
516
     */
517 1
    public function getLogoUri()
518
    {
519 1
        return $this->logo_uri;
520
    }
521
522
    /**
523
     * @inheritdoc
524
     */
525 1
    public function setLogoUri($logoUri)
526
    {
527 1
        $this->logo_uri = $logoUri;
528 1
        return $this;
529
    }
530
531
    /**
532
     * @inheritdoc
533
     */
534 1
    public function getTermsOfServiceUri()
535
    {
536 1
        return $this->tos_uri;
537
    }
538
539
    /**
540
     * @inheritdoc
541
     */
542 1
    public function setTermsOfServiceUri($tosUri)
543
    {
544 1
        $this->tos_uri = $tosUri;
545 1
        return $this;
546
    }
547
548
    /**
549
     * @inheritdoc
550
     */
551 1
    public function getContacts()
552
    {
553 1
        return $this->contacts;
554
    }
555
556
    /**
557
     * @inheritdoc
558
     */
559 1
    public function setContacts($contacts)
560
    {
561 1
        $this->contacts = $contacts;
562 1
        return $this;
563
    }
564
565
    /**
566
     * @inheritDoc
567
     */
568 1
    public function getGrantTypes()
569
    {
570 1
        return (int)$this->grant_types;
571
    }
572
573
    /**
574
     * @inheritDoc
575
     */
576 2
    public function setGrantTypes($grantTypes)
577
    {
578 2
        $grantTypeIds = array_flip(Oauth2Module::GRANT_TYPE_MAPPING);
579 2
        for ($i = (int)log(PHP_INT_MAX, 2); $i >= 0; $i--) {
580 2
            $grantTypeId = (int)pow(2, $i);
581 2
            if ($grantTypes & $grantTypeId) {
582 2
                if (!array_key_exists($grantTypeId, $grantTypeIds)) {
583 1
                    throw new InvalidArgumentException('Unknown Grant Type ID: ' . $grantTypeId);
584
                }
585
            }
586
        }
587
588 1
        $this->grant_types = $grantTypes;
589
    }
590
591
    /**
592
     * @inheritDoc
593
     */
594 2
    public function validateGrantType($grantTypeIdentifier)
595
    {
596 2
        $grantTypeId = Oauth2Module::getGrantTypeId($grantTypeIdentifier);
597 2
        if (empty($grantTypeId)) {
598 1
            throw new InvalidArgumentException('Unknown grant type "' . $grantTypeIdentifier . '".');
599
        }
600
601 1
        return (bool)($this->getGrantTypes() & $grantTypeId);
602
    }
603
604
    /**
605
     * @inheritDoc
606
     */
607 14
    public function validateAuthRequestScopes($scopeIdentifiers, &$unauthorizedScopes = [])
608
    {
609
        if (
610 14
            empty($scopeIdentifiers)
611
            // Quiet mode will always allow the request (scopes will silently be limited to the defined ones).
612 14
            || $this->getScopeAccess() === static::SCOPE_ACCESS_STRICT_QUIET
613
        ) {
614 4
            $unauthorizedScopes = [];
615 4
            return true;
616
        }
617
618 10
        $allowedScopeIdentifiers = array_map(
619 10
            fn($scope) => $scope->getIdentifier(),
620 10
            $this->getAllowedScopes($scopeIdentifiers)
621 10
        );
622
623 9
        $unauthorizedScopes = array_values(array_diff($scopeIdentifiers, $allowedScopeIdentifiers));
624
625 9
        return empty($unauthorizedScopes);
626
    }
627
628
    /**
629
     * @inheritDoc
630
     * @throws InvalidConfigException
631
     */
632 15
    public function getAllowedScopes($requestedScopeIdentifiers = [])
633
    {
634
        /** @var Oauth2ClientScopeInterface $clientScopeClass */
635 15
        $clientScopeClass = DiHelper::getValidatedClassName(Oauth2ClientScopeInterface::class);
636 15
        $clientScopeTableName = $clientScopeClass::tableName();
637
        /** @var Oauth2ScopeInterface $scopeClass */
638 15
        $scopeClass = DiHelper::getValidatedClassName(Oauth2ScopeInterface::class);
639 15
        $scopeTableName = $scopeClass::tableName();
640
641 15
        $possibleScopesConditions = [
642
            // Default scopes defined for this client.
643 15
            ['AND',
644 15
                [$clientScopeTableName . '.client_id' => $this->getPrimaryKey()],
645 15
                [$clientScopeTableName . '.enabled' => 1],
646 15
                ['OR',
647 15
                    ...(
648 15
                        !empty($requestedScopeIdentifiers)
649 12
                            ? [[$scopeTableName . '.identifier' => $requestedScopeIdentifiers]]
650
                            : []
651 15
                    ),
652 15
                    ['NOT', [
653 15
                        $clientScopeTableName . '.applied_by_default' => Oauth2ScopeInterface::APPLIED_BY_DEFAULT_NO
654 15
                    ]],
655 15
                    ['AND',
656 15
                        [$clientScopeTableName . '.applied_by_default' => null],
657 15
                        ['NOT', [
658 15
                            $scopeTableName . '.applied_by_default' => Oauth2ScopeInterface::APPLIED_BY_DEFAULT_NO
659 15
                        ]],
660 15
                    ],
661 15
                ],
662 15
            ],
663 15
        ];
664
665 15
        $scopeAccess = $this->getScopeAccess();
666 15
        if ($scopeAccess === Oauth2Client::SCOPE_ACCESS_PERMISSIVE) {
667
            // Default scopes defined by scope for all client.
668 4
            $possibleScopesConditions[] = ['AND',
669 4
                [$clientScopeTableName . '.client_id' => null],
670 4
                ['OR',
671 4
                    ...(
672 4
                        !empty($requestedScopeIdentifiers)
673 3
                            ? [[$scopeTableName . '.identifier' => $requestedScopeIdentifiers]]
674
                            : []
675 4
                    ),
676 4
                    ['NOT', [$scopeTableName . '.applied_by_default' => Oauth2ScopeInterface::APPLIED_BY_DEFAULT_NO]],
677 4
                ],
678 4
            ];
679
        } elseif (
680 11
            ($scopeAccess !== Oauth2Client::SCOPE_ACCESS_STRICT)
681 11
            && ($scopeAccess !== Oauth2Client::SCOPE_ACCESS_STRICT_QUIET)
682
        ) {
683
            // safeguard against unknown types.
684 1
            throw new \LogicException('Unknown scope_access: "' . $scopeAccess . '".');
685
        }
686
687 14
        return $scopeClass::find()
688 14
            ->joinWith('clientScopes', true)
689 14
            ->enabled()
690 14
            ->andWhere(['OR', ...$possibleScopesConditions])
691 14
            ->orderBy('id')
692 14
            ->all();
693
    }
694
695
    /**
696
     * @inheritdoc
697
     * @return array{
0 ignored issues
show
Documentation Bug introduced by
The doc comment array{ at position 2 could not be parsed: the token is null at position 2.
Loading history...
698
     *     'unaffected': Oauth2ClientScopeInterface[],
699
     *     'new': Oauth2ClientScopeInterface[],
700
     *     'updated': Oauth2ClientScopeInterface[],
701
     *     'deleted': Oauth2ClientScopeInterface[],
702
     * }
703
     */
704 11
    public function syncClientScopes($scopes, $scopeRepository)
705
    {
706 11
        if (is_string($scopes)) {
707 2
            $scopes = explode(' ', $scopes);
708 9
        } elseif ($scopes === null) {
709 1
            $scopes = [];
710 8
        } elseif (!is_array($scopes)) {
711 1
            throw new InvalidArgumentException('$scopes must be a string, an array or null.');
712
        }
713
714
        /** @var class-string<Oauth2ClientScopeInterface> $clientScopeClass */
715 10
        $clientScopeClass = DiHelper::getValidatedClassName(Oauth2ClientScopeInterface::class);
716
717
        /** @var Oauth2ClientScopeInterface[] $origClientScopes */
718 10
        $origClientScopes = $clientScopeClass::findAll([
719 10
            'client_id' => $this->getPrimaryKey(),
720 10
        ]);
721
722 10
        $origClientScopes = array_combine(
723 10
            array_map(
724 10
                fn(Oauth2ClientScopeInterface $clientScope) => implode('-', $clientScope->getPrimaryKey(true)),
725 10
                $origClientScopes
726 10
            ),
727 10
            $origClientScopes
728 10
        );
729
730
        /** @var Oauth2ClientScopeInterface[] $clientScopes */
731 10
        $clientScopes = [];
732
733 10
        foreach ($scopes as $key => $value) {
734 9
            if ($value instanceof Oauth2ClientScopeInterface) {
735 2
                $clientScope = $value;
736 2
                $clientScope->client_id = $this->getPrimaryKey(); // Ensure PK is set.
0 ignored issues
show
Bug introduced by
Accessing client_id on the interface rhertogh\Yii2Oauth2Serve...th2ClientScopeInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
737 2
                $pkIndex = implode('-', $clientScope->getPrimaryKey(true));
738 2
                if (array_key_exists($pkIndex, $origClientScopes)) {
739
                    // Overwrite orig (might still be considered "unchanged" when new ClientScope is not "dirty").
740 2
                    $origClientScopes[$pkIndex] = $clientScope;
741
                }
742
            } else {
743
744 7
                $scopeIdentifier = null;
745 7
                $clientScopeConfig = [
746 7
                    'client_id' => $this->getPrimaryKey(),
747 7
                ];
748
749 7
                if (is_string($value)) {
750 3
                    $scopeIdentifier = $value;
751 4
                } elseif ($value instanceof Oauth2ScopeInterface) {
752 2
                    $scopePk = $value->getPrimaryKey();
753 2
                    if ($scopePk) {
754 1
                        $clientScopeConfig = ArrayHelper::merge(
755 1
                            $clientScopeConfig,
756 1
                            ['scope_id' => $scopePk]
757 1
                        );
758
                    } else {
759
                        // New model, using identifier.
760 2
                        $scopeIdentifier = $value->getIdentifier();
761
                    }
762 2
                } elseif (is_array($value)) {
763 1
                    $clientScopeConfig = ArrayHelper::merge(
764 1
                        $clientScopeConfig,
765 1
                        $value,
766 1
                    );
767 1
                    if (empty($clientScopeConfig['scope_id'])) {
768 1
                        $scopeIdentifier = $key;
769
                    }
770
                } else {
771 1
                    throw new InvalidArgumentException(
772 1
                        'If $scopes is an array, its values must be a string, array or an instance of '
773 1
                        . Oauth2ClientScopeInterface::class . ' or ' . Oauth2ScopeInterface::class . '.'
774 1
                    );
775
                }
776
777 6
                if (isset($scopeIdentifier)) {
778 4
                    $scope = $scopeRepository->getScopeEntityByIdentifier($scopeIdentifier);
779 4
                    if (empty($scope)) {
780 1
                        throw new InvalidArgumentException('No scope with identifier "'
781 1
                            . $scopeIdentifier . '" found.');
782
                    }
783 3
                    if (!($scope instanceof Oauth2ScopeInterface)) {
784
                        throw new InvalidConfigException(get_class($scope) . ' must implement ' . Oauth2ScopeInterface::class);
785
                    }
786 3
                    $clientScopeConfig['scope_id'] = $scope->getPrimaryKey();
787
                } else {
788 3
                    if (empty($clientScopeConfig['scope_id'])) {
789 1
                        throw new InvalidArgumentException('Element ' . $key
790 1
                            . ' in $scope should specify either the scope id or its identifier.');
791
                    }
792
                }
793
794 4
                $pkIndex = $clientScopeConfig['client_id'] . '-' . $clientScopeConfig['scope_id'];
795 4
                if (array_key_exists($pkIndex, $origClientScopes)) {
796 4
                    $clientScope = $origClientScopes[$pkIndex];
797 4
                    $clientScope->setAttributes($clientScopeConfig, false);
798
                } else {
799
                    /** @var Oauth2ClientScopeInterface $clientScope */
800 4
                    $clientScope = Yii::createObject(ArrayHelper::merge(
801 4
                        ['class' => $clientScopeClass],
802 4
                        $clientScopeConfig
803 4
                    ));
804
                }
805
            }
806
807 6
            $pkIndex = implode('-', $clientScope->getPrimaryKey(true));
808 6
            $clientScopes[$pkIndex] = $clientScope;
809
        }
810
811 7
        $transaction = static::getDb()->beginTransaction();
812
        try {
813
            // Delete records no longer present in the provided data.
814
            /** @var self[]|array[] $deleteClientScopes */
815 7
            $deleteClientScopes = array_diff_key($origClientScopes, $clientScopes);
816 7
            foreach ($deleteClientScopes as $deleteClientScope) {
817 6
                $deleteClientScope->delete();
818
            }
819
820
            // Create records not present in the provided data.
821 7
            $createClientScopes = array_diff_key($clientScopes, $origClientScopes);
822 7
            foreach ($createClientScopes as $createClientScope) {
823 6
                $createClientScope->persist();
824
            }
825
826
            // Update existing records if needed.
827 6
            $unaffectedClientScopes = [];
828 6
            $updatedClientScopes = [];
829 6
            foreach (array_intersect_key($origClientScopes, $clientScopes) as $key => $existingClientScope) {
830 5
                if ($existingClientScope->getDirtyAttributes()) {
831 2
                    $existingClientScope->persist();
832 2
                    $updatedClientScopes[$key] = $existingClientScope;
833
                } else {
834 5
                    $unaffectedClientScopes[$key] = $existingClientScope;
835
                }
836
            }
837
838 6
            $transaction->commit();
839 1
        } catch (\Exception $e) {
840 1
            $transaction->rollBack();
841 1
            throw $e;
842
        }
843
844 6
        return [
845 6
            'unaffected' => $unaffectedClientScopes,
846 6
            'new' => $createClientScopes,
847 6
            'updated' => $updatedClientScopes,
848 6
            'deleted' => $deleteClientScopes,
849 6
        ];
850
    }
851
}
852