JwtService::save()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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