AuthCodeService   A
last analyzed

Complexity

Total Complexity 38

Size/Duplication

Total Lines 231
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

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

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getAuthCodeKey() 0 4 1
A save() 0 9 2
B insert() 0 50 9
F update() 0 78 18
B findOne() 0 31 6
A delete() 0 17 2
1
<?php
2
/**
3
 * AuthCodeService.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\AuthCodeModelInterface;
20
use sweelix\oauth2\server\interfaces\AuthCodeServiceInterface;
21
use yii\db\Exception as DatabaseException;
22
use Yii;
23
24
/**
25
 * This is the auth code service for redis
26
 *  database structure
27
 *    * oauth2:authCodes:<aid> : hash (AuthCode)
28
 *
29
 * @author Philippe Gaultier <[email protected]>
30
 * @copyright 2010-2017 Philippe Gaultier
31
 * @license http://www.sweelix.net/license license
32
 * @version 1.2.0
33
 * @link http://www.sweelix.net
34
 * @package sweelix\oauth2\server\services\redis
35
 * @since 1.0.0
36
 */
37
class AuthCodeService extends BaseService implements AuthCodeServiceInterface
38
{
39
    /**
40
     * @param string $aid auth code ID
41
     * @return string auth code Key
42
     * @since 1.0.0
43
     */
44
    protected function getAuthCodeKey($aid)
45
    {
46
        return $this->namespace . ':' . $aid;
47
    }
48
49
    /**
50
     * @inheritdoc
51
     */
52
    public function save(AuthCodeModelInterface $authCode, $attributes)
53
    {
54
        if ($authCode->getIsNewRecord()) {
55
            $result = $this->insert($authCode, $attributes);
56
        } else {
57
            $result = $this->update($authCode, $attributes);
58
        }
59
        return $result;
60
    }
61
62
    /**
63
     * Save Auth Code
64
     * @param AuthCodeModelInterface $authCode
65
     * @param null|array $attributes attributes to save
66
     * @return bool
67
     * @throws DatabaseException
68
     * @throws DuplicateIndexException
69
     * @throws DuplicateKeyException
70
     * @since 1.0.0
71
     */
72
    protected function insert(AuthCodeModelInterface $authCode, $attributes)
73
    {
74
        $result = false;
75
        if (!$authCode->beforeSave(true)) {
76
            return $result;
77
        }
78
        $authCodeKey = $this->getAuthCodeKey($authCode->getKey());
79
        //check if record exists
80
        $entityStatus = (int)$this->db->executeCommand('EXISTS', [$authCodeKey]);
81
        if ($entityStatus === 1) {
82
            throw new DuplicateKeyException('Duplicate key "'.$authCodeKey.'"');
83
        }
84
85
        $values = $authCode->getDirtyAttributes($attributes);
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 72 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...
86
        $redisParameters = [$authCodeKey];
87
        $this->setAttributesDefinitions($authCode->attributesDefinition());
88
        $expire = null;
89
        foreach ($values as $key => $value)
90
        {
91
            if ($key === 'expiry') {
92
                $expire = $value;
93
            }
94
            if ($value !== null) {
95
                $redisParameters[] = $key;
96
                $redisParameters[] = $this->convertToDatabase($key, $value);
97
            }
98
        }
99
        //TODO: use EXEC/MULTI to avoid errors
100
        $transaction = $this->db->executeCommand('MULTI');
101
        if ($transaction === true) {
102
            try {
103
                $this->db->executeCommand('HMSET', $redisParameters);
104
                if ($expire !== null) {
105
                    $this->db->executeCommand('EXPIREAT', [$authCodeKey, $expire]);
106
                }
107
                $this->db->executeCommand('EXEC');
108
            } catch (DatabaseException $e) {
109
                // @codeCoverageIgnoreStart
110
                // we have a REDIS exception, we should not discard
111
                Yii::debug('Error while inserting entity', __METHOD__);
112
                throw $e;
113
                // @codeCoverageIgnoreEnd
114
            }
115
        }
116
        $changedAttributes = array_fill_keys(array_keys($values), null);
117
        $authCode->setOldAttributes($values);
118
        $authCode->afterSave(true, $changedAttributes);
119
        $result = true;
120
        return $result;
121
    }
122
123
124
    /**
125
     * Update Auth Code
126
     * @param AuthCodeModelInterface $authCode
127
     * @param null|array $attributes attributes to save
128
     * @return bool
129
     * @throws DatabaseException
130
     * @throws DuplicateIndexException
131
     * @throws DuplicateKeyException
132
     */
133
    protected function update(AuthCodeModelInterface $authCode, $attributes)
134
    {
135
        if (!$authCode->beforeSave(false)) {
136
            return false;
137
        }
138
139
        $values = $authCode->getDirtyAttributes($attributes);
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 133 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...
140
        $modelKey = $authCode->key();
141
        $authCodeId = isset($values[$modelKey]) ? $values[$modelKey] : $authCode->getKey();
142
        $authCodeKey = $this->getAuthCodeKey($authCodeId);
143
144
145
        if (isset($values[$modelKey]) === true) {
146
            $newAuthCodeKey = $this->getAuthCodeKey($values[$modelKey]);
147
            $entityStatus = (int)$this->db->executeCommand('EXISTS', [$newAuthCodeKey]);
148
            if ($entityStatus === 1) {
149
                throw new DuplicateKeyException('Duplicate key "'.$newAuthCodeKey.'"');
150
            }
151
        }
152
153
        $this->db->executeCommand('MULTI');
154
        try {
155
            if (array_key_exists($modelKey, $values) === true) {
156
                $oldId = $authCode->getOldKey();
157
                $oldAuthCodeKey = $this->getAuthCodeKey($oldId);
158
159
                $this->db->executeCommand('RENAMENX', [$oldAuthCodeKey, $authCodeKey]);
160
            }
161
162
            $redisUpdateParameters = [$authCodeKey];
163
            $redisDeleteParameters = [$authCodeKey];
164
            $this->setAttributesDefinitions($authCode->attributesDefinition());
165
            $expire = $authCode->expiry;
0 ignored issues
show
Bug introduced by
Accessing expiry on the interface sweelix\oauth2\server\in...\AuthCodeModelInterface 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...
166
            foreach ($values as $key => $value)
167
            {
168
                if ($value === null) {
169
                    if ($key === 'expiry') {
170
                        $expire = false;
171
                    }
172
                    $redisDeleteParameters[] = $key;
173
                } else {
174
                    if (($key === 'expiry') && ($value > 0)) {
175
                        $expire = $value;
176
                    }
177
                    $redisUpdateParameters[] = $key;
178
                    $redisUpdateParameters[] = $this->convertToDatabase($key, $value);
179
                }
180
            }
181
            if (count($redisDeleteParameters) > 1) {
182
                $this->db->executeCommand('HDEL', $redisDeleteParameters);
183
            }
184
            if (count($redisUpdateParameters) > 1) {
185
                $this->db->executeCommand('HMSET', $redisUpdateParameters);
186
            }
187
            if ($expire === false) {
188
                $this->db->executeCommand('PERSIST', [$authCodeKey]);
189
            } elseif ($expire > 0) {
190
                $this->db->executeCommand('EXPIREAT', [$authCodeKey, $expire]);
191
            }
192
193
            $this->db->executeCommand('EXEC');
194
        } catch (DatabaseException $e) {
195
            // @codeCoverageIgnoreStart
196
            // we have a REDIS exception, we should not discard
197
            Yii::debug('Error while updating entity', __METHOD__);
198
            throw $e;
199
            // @codeCoverageIgnoreEnd
200
        }
201
202
        $changedAttributes = [];
203
        foreach ($values as $name => $value) {
204
            $oldAttributes = $authCode->getOldAttributes();
205
            $changedAttributes[$name] = isset($oldAttributes[$name]) ? $oldAttributes[$name] : null;
206
            $authCode->setOldAttribute($name, $value);
207
        }
208
        $authCode->afterSave(false, $changedAttributes);
209
        return true;
210
    }
211
212
    /**
213
     * @inheritdoc
214
     */
215
    public function findOne($key)
216
    {
217
        $record = null;
218
        $authCodeKey = $this->getAuthCodeKey($key);
219
        $authCodeExists = (bool)$this->db->executeCommand('EXISTS', [$authCodeKey]);
220
        if ($authCodeExists === true) {
221
            $authCodeData = $this->db->executeCommand('HGETALL', [$authCodeKey]);
222
            $record = Yii::createObject('sweelix\oauth2\server\interfaces\AuthCodeModelInterface');
223
            /** @var AuthCodeModelInterface $record */
224
            $properties = $record->attributesDefinition();
225
            $this->setAttributesDefinitions($properties);
226
            $attributes = [];
227
            for ($i = 0; $i < count($authCodeData); $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...
228
                if (isset($properties[$authCodeData[$i]]) === true) {
229
                    $authCodeData[$i + 1] = $this->convertToModel($authCodeData[$i], $authCodeData[($i + 1)]);
230
                    $record->setAttribute($authCodeData[$i], $authCodeData[$i + 1]);
231
                    $attributes[$authCodeData[$i]] = $authCodeData[$i + 1];
232
                // @codeCoverageIgnoreStart
233
                } elseif ($record->canSetProperty($authCodeData[$i])) {
234
                    // TODO: find a way to test attribute population
235
                    $record->{$authCodeData[$i]} = $authCodeData[$i + 1];
236
                }
237
                // @codeCoverageIgnoreEnd
238
            }
239
            if (empty($attributes) === false) {
240
                $record->setOldAttributes($attributes);
241
            }
242
            $record->afterFind();
243
        }
244
        return $record;
245
    }
246
247
    /**
248
     * @inheritdoc
249
     */
250
    public function delete(AuthCodeModelInterface $authCode)
251
    {
252
        $result = false;
253
        if ($authCode->beforeDelete()) {
254
            $this->db->executeCommand('MULTI');
255
            $id = $authCode->getOldKey();
256
            $authCodeKey = $this->getAuthCodeKey($id);
257
258
            $this->db->executeCommand('DEL', [$authCodeKey]);
259
            //TODO: check results to return correct information
260
            $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...
261
            $authCode->setIsNewRecord(true);
262
            $authCode->afterDelete();
263
            $result = true;
264
        }
265
        return $result;
266
    }
267
}
268