safeDown()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 0
c 1
b 0
f 0
dl 0
loc 2
ccs 0
cts 1
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, array_filter(array_map('trim', 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
                array_filter(array_map('trim', 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->getCryptographer());
118
            } else {
119
                $client->setType(Oauth2ClientInterface::TYPE_PUBLIC);
120
            }
121
122
            $client->setClientCredentialsGrantUserId($clientData['user_id'] ?? null);
123
124
            $scopes = isset($clientData['scope'])
125
                ? array_filter(array_map('trim', explode(' ', $clientData['scope'])))
126
                : [];
127
128
            $client
129
                ->persist()
130
                ->syncClientScopes($scopes, $module->getScopeRepository());
131
132
            $newClients[] = $client;
133
        }
134
135
        if ($newClients) {
136
            $controller->stdout('Created ' . count($newClients) . ' new client(s):' . PHP_EOL);
137
            $controller->stdout($this->generateClientsTable($newClients));
138
            $controller->stdout(PHP_EOL);
139
        }
140
141
        if ($existingClients) {
142
            $controller->stdout(count($existingClients) . ' existing '
143
                . (count($existingClients) > 1 ? 'clients were' : 'client was' ) . ' skipped: '
144
                . implode(', ', array_column($existingClients, 'identifier')) . PHP_EOL);
145
        }
146
147
        if ($warnings) {
148
            $controller->stdout('Warnings:' . PHP_EOL, Console::FG_YELLOW);
149
            foreach ($warnings as $warning) {
150
                $controller->stdout(' - ' . $warning . PHP_EOL, Console::FG_YELLOW);
151
            }
152
            $controller->stdout(PHP_EOL);
153
        }
154
    }
155
156
    protected function getImportClientData()
157
    {
158
        return (new Query())
159
            ->from($this->getImportClientTable())
160
            ->all($this->db);
161
    }
162
163
    protected function getImportClientTable()
164
    {
165
        $clientTable = $this->config['clientTable'] ?? null;
166
        if (empty($clientTable)) {
167
            throw new InvalidConfigException('$config[\'clientTable\'] must be set.');
168
        }
169
        return $clientTable;
170
    }
171
172
    /**
173
     * @inheritDoc
174
     */
175
    public function safeDown()
176
    {
177
        // Note: Clients and/or Scopes are never removed.
178
    }
179
}
180