ScopeService   A
last analyzed

Complexity

Total Complexity 38

Size/Duplication

Total Lines 277
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 38
lcom 1
cbo 5
dl 0
loc 277
c 0
b 0
f 0
rs 9.36

10 Methods

Rating   Name   Duplication   Size   Complexity  
A getScopeKey() 0 4 1
A getScopeListKey() 0 4 1
A getScopeDefaultListKey() 0 4 1
B findOne() 0 31 6
A findAvailableScopeIds() 0 5 1
A findDefaultScopeIds() 0 6 1
A delete() 0 22 2
A save() 0 9 2
B insert() 0 49 8
F update() 0 81 15
1
<?php
2
/**
3
 * ScopeService.php
4
 *
5
 * PHP version 5.6+
6
 *
7
 * @author Philippe Gaultier <[email protected]>
8
 * @copyright 2010-2017 Philippe Gaultier
9
 * @license http://www.sweelix.net/license license
10
 * @version 1.2.0
11
 * @link http://www.sweelix.net
12
 * @package sweelix\oauth2\server\services\redis
13
 */
14
15
namespace sweelix\oauth2\server\services\redis;
16
17
use sweelix\oauth2\server\exceptions\DuplicateIndexException;
18
use sweelix\oauth2\server\exceptions\DuplicateKeyException;
19
use sweelix\oauth2\server\interfaces\ScopeModelInterface;
20
use sweelix\oauth2\server\models\Scope;
21
use sweelix\oauth2\server\interfaces\ScopeServiceInterface;
22
use yii\db\Exception as DatabaseException;
23
use Yii;
24
25
/**
26
 * This is the scope service for redis
27
 *  database structure
28
 *    * oauth2:scopes:<sid> : hash (Scope)
29
 *    * oauth2:scopes:keys : set scopeIds
30
 *    * oauth2:scopes:defaultkeys : set default scopeIds
31
 *
32
 * @author Philippe Gaultier <[email protected]>
33
 * @copyright 2010-2017 Philippe Gaultier
34
 * @license http://www.sweelix.net/license license
35
 * @version 1.2.0
36
 * @link http://www.sweelix.net
37
 * @package sweelix\oauth2\server\services\redis
38
 * @since 1.0.0
39
 */
40
class ScopeService extends BaseService implements ScopeServiceInterface
41
{
42
43
    /**
44
     * @param string $sid scope ID
45
     * @return string scope Key
46
     * @since 1.0.0
47
     */
48
    protected function getScopeKey($sid)
49
    {
50
        return $this->namespace . ':' . $sid;
51
    }
52
53
    /**
54
     * @return string key of all scopes list
55
     * @since 1.0.0
56
     */
57
    protected function getScopeListKey()
58
    {
59
        return $this->namespace . ':keys';
60
    }
61
62
    /**
63
     * @return string key of default scopes list
64
     * @since 1.0.0
65
     */
66
    protected function getScopeDefaultListKey()
67
    {
68
        return $this->namespace . ':defaultkeys';
69
    }
70
71
    /**
72
     * @inheritdoc
73
     */
74
    public function save(ScopeModelInterface $scope, $attributes)
75
    {
76
        if ($scope->getIsNewRecord()) {
77
            $result = $this->insert($scope, $attributes);
78
        } else {
79
            $result = $this->update($scope, $attributes);
80
        }
81
        return $result;
82
    }
83
84
    /**
85
     * Save Scope
86
     * @param ScopeModelInterface $scope
87
     * @param null|array $attributes attributes to save
88
     * @return bool
89
     * @throws DatabaseException
90
     * @throws DuplicateIndexException
91
     * @throws DuplicateKeyException
92
     * @since 1.0.0
93
     */
94
    protected function insert(ScopeModelInterface $scope, $attributes)
95
    {
96
        $result = false;
97
        if (!$scope->beforeSave(true)) {
98
            return $result;
99
        }
100
        $scopeKey = $this->getScopeKey($scope->getKey());
101
        $scopeListKey = $this->getScopeListKey();
102
        $scopeDefaultListKey = $this->getScopeDefaultListKey();
103
        //check if record exists
104
        $entityStatus = (int)$this->db->executeCommand('EXISTS', [$scopeKey]);
105
        if ($entityStatus === 1) {
106
            throw new DuplicateKeyException('Duplicate key "'.$scopeKey.'"');
107
        }
108
109
        $values = $scope->getDirtyAttributes($attributes);
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 94 can also be of type array; however, sweelix\oauth2\server\in...e::getDirtyAttributes() does only seem to accept array<integer,string>|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
110
        $redisParameters = [$scopeKey];
111
        $this->setAttributesDefinitions($scope->attributesDefinition());
112
        foreach ($values as $key => $value)
113
        {
114
            if ($value !== null) {
115
                $redisParameters[] = $key;
116
                $redisParameters[] = $this->convertToDatabase($key, $value);
117
            }
118
        }
119
        //TODO: use EXEC/MULTI to avoid errors
120
        $transaction = $this->db->executeCommand('MULTI');
121
        if ($transaction === true) {
122
            try {
123
                $this->db->executeCommand('HMSET', $redisParameters);
124
                $this->db->executeCommand('SADD', [$scopeListKey, $scope->getKey()]);
125
                if ($scope->isDefault === true) {
0 ignored issues
show
Bug introduced by
Accessing isDefault on the interface sweelix\oauth2\server\in...ces\ScopeModelInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
126
                    $this->db->executeCommand('SADD', [$scopeDefaultListKey, $scope->getKey()]);
127
                }
128
                $this->db->executeCommand('EXEC');
129
            } catch (DatabaseException $e) {
130
                // @codeCoverageIgnoreStart
131
                // we have a REDIS exception, we should not discard
132
                Yii::debug('Error while inserting entity', __METHOD__);
133
                throw $e;
134
                // @codeCoverageIgnoreEnd
135
            }
136
        }
137
        $changedAttributes = array_fill_keys(array_keys($values), null);
138
        $scope->setOldAttributes($values);
139
        $scope->afterSave(true, $changedAttributes);
140
        $result = true;
141
        return $result;
142
    }
143
144
145
    /**
146
     * Update ScopeModelInterface
147
     * @param Scope $scope
148
     * @param null|array $attributes attributes to save
149
     * @return bool
150
     * @throws DatabaseException
151
     * @throws DuplicateIndexException
152
     * @throws DuplicateKeyException
153
     */
154
    protected function update(ScopeModelInterface $scope, $attributes)
155
    {
156
        if (!$scope->beforeSave(false)) {
157
            return false;
158
        }
159
160
        $values = $scope->getDirtyAttributes($attributes);
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 154 can also be of type array; however, sweelix\oauth2\server\in...e::getDirtyAttributes() does only seem to accept array<integer,string>|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
161
        $modelKey = $scope->key();
162
        $scopeId = isset($values[$modelKey]) ? $values[$modelKey] : $scope->getKey();
163
        $scopeKey = $this->getScopeKey($scopeId);
164
        $scopeListKey = $this->getScopeListKey();
165
        $scopeDefaultListKey = $this->getScopeDefaultListKey();
166
167
168
        if (isset($values[$modelKey]) === true) {
169
            $newScopeKey = $this->getScopeKey($values[$modelKey]);
170
            $entityStatus = (int)$this->db->executeCommand('EXISTS', [$newScopeKey]);
171
            if ($entityStatus === 1) {
172
                throw new DuplicateKeyException('Duplicate key "'.$newScopeKey.'"');
173
            }
174
        }
175
176
        $this->db->executeCommand('MULTI');
177
        try {
178
            $reAddKeyInList = false;
179
            if (array_key_exists($modelKey, $values) === true) {
180
                $oldId = $scope->getOldKey();
181
                $oldScopeKey = $this->getScopeKey($oldId);
182
183
                $this->db->executeCommand('RENAMENX', [$oldScopeKey, $scopeKey]);
184
                $this->db->executeCommand('SREM', [$scopeListKey, $oldScopeKey]);
185
                $this->db->executeCommand('SREM', [$scopeDefaultListKey, $oldScopeKey]);
186
                $reAddKeyInList = true;
187
            }
188
189
            $redisUpdateParameters = [$scopeKey];
190
            $redisDeleteParameters = [$scopeKey];
191
            $this->setAttributesDefinitions($scope->attributesDefinition());
192
            foreach ($values as $key => $value)
193
            {
194
                if ($value === null) {
195
                    $redisDeleteParameters[] = $key;
196
                } else {
197
                    $redisUpdateParameters[] = $key;
198
                    $redisUpdateParameters[] = $this->convertToDatabase($key, $value);
199
                }
200
            }
201
            if (count($redisDeleteParameters) > 1) {
202
                $this->db->executeCommand('HDEL', $redisDeleteParameters);
203
            }
204
            if (count($redisUpdateParameters) > 1) {
205
                $this->db->executeCommand('HMSET', $redisUpdateParameters);
206
            }
207
208
            if ($reAddKeyInList === true) {
209
                $this->db->executeCommand('SADD', [$scopeListKey, $scopeId]);
210
            }
211
            if ($scope->isDefault === true) {
0 ignored issues
show
Bug introduced by
Accessing isDefault on the interface sweelix\oauth2\server\in...ces\ScopeModelInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
212
                $this->db->executeCommand('SADD', [$scopeDefaultListKey, $scopeId]);
213
            } else {
214
                $this->db->executeCommand('SREM', [$scopeDefaultListKey, $scopeId]);
215
            }
216
217
            $this->db->executeCommand('EXEC');
218
        } catch (DatabaseException $e) {
219
            // @codeCoverageIgnoreStart
220
            // we have a REDIS exception, we should not discard
221
            Yii::debug('Error while updating entity', __METHOD__);
222
            throw $e;
223
            // @codeCoverageIgnoreEnd
224
        }
225
226
        $changedAttributes = [];
227
        foreach ($values as $name => $value) {
228
            $oldAttributes = $scope->getOldAttributes();
229
            $changedAttributes[$name] = isset($oldAttributes[$name]) ? $oldAttributes[$name] : null;
230
            $scope->setOldAttribute($name, $value);
231
        }
232
        $scope->afterSave(false, $changedAttributes);
233
        return true;
234
    }
235
236
    /**
237
     * @inheritdoc
238
     */
239
    public function findOne($key)
240
    {
241
        $record = null;
242
        $scopeKey = $this->getScopeKey($key);
243
        $scopeExists = (bool)$this->db->executeCommand('EXISTS', [$scopeKey]);
244
        if ($scopeExists === true) {
245
            $scopeData = $this->db->executeCommand('HGETALL', [$scopeKey]);
246
            $record = Yii::createObject('sweelix\oauth2\server\interfaces\ScopeModelInterface');
247
            /** @var ScopeModelInterface $record */
248
            $properties = $record->attributesDefinition();
249
            $this->setAttributesDefinitions($properties);
250
            $attributes = [];
251
            for ($i = 0; $i < count($scopeData); $i += 2) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
252
                if (isset($properties[$scopeData[$i]]) === true) {
253
                    $scopeData[$i + 1] = $this->convertToModel($scopeData[$i], $scopeData[($i + 1)]);
254
                    $record->setAttribute($scopeData[$i], $scopeData[$i + 1]);
255
                    $attributes[$scopeData[$i]] = $scopeData[$i + 1];
256
                // @codeCoverageIgnoreStart
257
                } elseif ($record->canSetProperty($scopeData[$i])) {
258
                    // TODO: find a way to test attribute population
259
                    $record->{$scopeData[$i]} = $scopeData[$i + 1];
260
                }
261
                // @codeCoverageIgnoreEnd
262
            }
263
            if (empty($attributes) === false) {
264
                $record->setOldAttributes($attributes);
265
            }
266
            $record->afterFind();
267
        }
268
        return $record;
269
    }
270
271
    /**
272
     * @inheritdoc
273
     */
274
    public function findAvailableScopeIds()
275
    {
276
        $scopeListKey = $this->getScopeListKey();
277
        return $this->db->executeCommand('SMEMBERS', [$scopeListKey]);
278
    }
279
280
    /**
281
     * @inheritdoc
282
     */
283
    public function findDefaultScopeIds($clientId = null)
284
    {
285
        //TODO: add default scopes for clients
286
        $scopeDefaultListKey = $this->getScopeDefaultListKey();
287
        return $this->db->executeCommand('SMEMBERS', [$scopeDefaultListKey]);
288
    }
289
290
    /**
291
     * @inheritdoc
292
     */
293
    public function delete(ScopeModelInterface $scope)
294
    {
295
        $result = false;
296
        if ($scope->beforeDelete()) {
297
            $this->db->executeCommand('MULTI');
298
            $id = $scope->getOldKey();
299
            $scopeKey = $this->getScopeKey($id);
300
            $scopeListKey = $this->getScopeListKey();
301
            $scopeDefaultListKey = $this->getScopeDefaultListKey();
302
303
304
            $this->db->executeCommand('DEL', [$scopeKey]);
305
            $this->db->executeCommand('SREM', [$scopeListKey, $id]);
306
            $this->db->executeCommand('SREM', [$scopeDefaultListKey, $id]);
307
            //TODO: check results to return correct information
308
            $queryResult = $this->db->executeCommand('EXEC');
0 ignored issues
show
Unused Code introduced by
$queryResult is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
309
            $scope->setIsNewRecord(true);
310
            $scope->afterDelete();
311
            $result = true;
312
        }
313
        return $result;
314
    }
315
316
}
317