Passed
Push — master ( 207765...57309d )
by Rutger
03:12
created

getImportClientData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
ccs 0
cts 4
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
namespace rhertogh\Yii2Oauth2Server\migrations\import;
4
5
use rhertogh\Yii2Oauth2Server\controllers\console\base\traits\GenerateClientsTableTrait;
6
use rhertogh\Yii2Oauth2Server\helpers\DiHelper;
7
use rhertogh\Yii2Oauth2Server\interfaces\models\Oauth2ClientInterface;
8
use rhertogh\Yii2Oauth2Server\interfaces\models\Oauth2ScopeInterface;
9
use rhertogh\Yii2Oauth2Server\migrations\base\Oauth2BaseMigration;
10
use rhertogh\Yii2Oauth2Server\Oauth2Module;
11
use Yii;
12
use yii\base\InvalidConfigException;
13
use yii\db\Query;
14
use yii\helpers\Console;
15
16
/**
17
 * phpcs:disable Squiz.Classes.ValidClassName.NotCamelCaps
18
 * phpcs:disable Generic.Files.LineLength.TooLong
19
 */
20
abstract class Oauth2_FilshYii2Oauth2ServerImportMigration extends Oauth2BaseMigration
21
{
22
    use GenerateClientsTableTrait;
23
24
    /**
25
     * @inheritDoc
26
     */
27
    public static function generationIsActive($module)
28
    {
29
        return true;
30
    }
31
32
    /**
33
     * @inheritDoc
34
     */
35
    public function safeUp()
36
    {
37
        $controller = Yii::$app->controller;
0 ignored issues
show
Documentation Bug introduced by
It seems like Yii::app->controller can also be of type yii\web\Controller. However, the property $controller is declared as type yii\console\Controller. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
38
        $module = Oauth2Module::getInstance();
39
        if (empty($module)) {
40
            throw new InvalidConfigException('Oauth2Module is not instantiated. Is it added to the config in the "module" and "bootstrap" section?');
41
        }
42
43
        $clientsData = $this->getImportClientData();
44
45
        $controller->stdout('Found ' . count($clientsData) . ' client(s) for import.' . PHP_EOL);
46
47
        $scopeIdentifiers = [];
48
        foreach (array_column($clientsData, 'scope') as $scope) {
49
            if ($scope) {
50
                $scopeIdentifiers = array_merge($scopeIdentifiers, explode(' ', $scope));
51
            }
52
        }
53
        $scopeIdentifiers = array_unique($scopeIdentifiers);
54
55
        /** @var class-string<Oauth2ScopeInterface> $scopeClass */
56
        $scopeClass = DiHelper::getValidatedClassName(Oauth2ScopeInterface::class);
57
58
        $existingScopeIdentifiers = $scopeClass::find()->select('identifier')->column();
59
60
        $missingScopeIdentifiers = array_diff($scopeIdentifiers, $existingScopeIdentifiers);
61
62
        foreach ($missingScopeIdentifiers as $scopeIdentifier) {
63
            $scope = new $scopeClass([
64
                'identifier' => $scopeIdentifier,
65
            ]);
66
            $scope->persist();
67
        }
68
69
        if ($missingScopeIdentifiers) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $missingScopeIdentifiers of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
70
            $controller->stdout('Created ' . count($missingScopeIdentifiers) . ' new scope(s): '
71
                . implode(', ', $missingScopeIdentifiers) . PHP_EOL);
72
        }
73
74
        /** @var class-string<Oauth2ClientInterface> $clientClass */
75
        $clientClass = DiHelper::getValidatedClassName(Oauth2ClientInterface::class);
76
77
        $newClients = [];
78
        $existingClients = [];
79
        $warnings = [];
80
        foreach ($clientsData as $index => $clientData) {
81
            if (empty($clientData['client_id'])) {
82
                throw new InvalidConfigException('Empty `client_id` at row ' . ($index + 1));
83
            }
84
            $clientIdentifier = $clientData['client_id'];
85
            $client = $clientClass::findByIdentifier($clientIdentifier);
86
            if ($client) {
87
                $existingClients[] = $client;
88
                continue;
89
            } else {
90
                $client = new $clientClass([
91
                    'identifier' => $clientIdentifier,
92
                    'name' => $clientIdentifier,
93
                ]);
94
            }
95
96
            if (empty($clientData['redirect_uri'])) {
97
                throw new InvalidConfigException('Empty `redirect_uri` for client ' . $clientIdentifier);
98
            }
99
            $client->setRedirectUri($clientData['redirect_uri']);
100
101
            if (empty($clientData['grant_types'])) {
102
                throw new InvalidConfigException('Empty `grant_types` for client ' . $clientIdentifier);
103
            }
104
            $client->setGrantTypes(array_reduce(
105
                explode(' ', $clientData['grant_types']),
106
                fn ($grantType, $identifier) => $grantType |= Oauth2Module::getGrantTypeId($identifier),
107
            ));
108
109
            if ($clientData['client_secret']) {
110
                if (mb_strlen($clientData['client_secret']) < $client->getMinimumSecretLength()) {
111
                    $warnings[] = 'The client secret length for "' . $clientIdentifier . '" is less then the minimum of '
112
                        . $client->getMinimumSecretLength() . ' characters, you might want to set a stronger secret.';
113
                    $client->setMinimumSecretLength(1);
114
                }
115
                $client
116
                    ->setType(Oauth2ClientInterface::TYPE_CONFIDENTIAL)
117
                    ->setSecret($clientData['client_secret'], $module->getEncryptor());
118
            } else {
119
                $client->setType(Oauth2ClientInterface::TYPE_PUBLIC);
120
            }
121
122
            $client->setClientCredentialsGrantUserId($clientData['user_id'] ?? null);
123
124
            $scopes = isset($clientData['scope']) ? explode(' ', $clientData['scope']) : [];
125
126
            $client
127
                ->persist()
128
                ->syncClientScopes($scopes, $module->getScopeRepository());
129
130
            $newClients[] = $client;
131
        }
132
133
        if ($newClients) {
134
            $controller->stdout('Created ' . count($newClients) . ' new client(s):' . PHP_EOL);
135
            $controller->stdout($this->generateClientsTable($newClients));
136
            $controller->stdout(PHP_EOL);
137
        }
138
139
        if ($existingClients) {
140
            $controller->stdout(count($existingClients) . ' existing '
141
                . (count($existingClients) > 1 ? 'clients were' : 'client was' ) . ' skipped: '
142
                . implode(', ', array_column($existingClients, 'identifier')) . PHP_EOL);
143
        }
144
145
        if ($warnings) {
146
            $controller->stdout('Warnings:' . PHP_EOL, Console::FG_YELLOW);
147
            foreach ($warnings as $warning) {
148
                $controller->stdout(' - ' . $warning . PHP_EOL, Console::FG_YELLOW);
149
            }
150
            $controller->stdout(PHP_EOL);
151
        }
152
    }
153
154
    protected function getImportClientData()
155
    {
156
        return (new Query())
157
            ->from($this->getImportClientTable())
158
            ->all($this->db);
159
    }
160
161
    protected function getImportClientTable()
162
    {
163
        $clientTable = $this->config['clientTable'] ?? null;
164
        if (empty($clientTable)) {
165
            throw new InvalidConfigException('$config[\'clientTable\'] must be set.');
166
        }
167
        return $clientTable;
168
    }
169
170
    /**
171
     * @inheritDoc
172
     */
173
    public function safeDown()
174
    {
175
        // Note: Clients and/or Scopes are never removed.
176
    }
177
}
178