AuthCodeService::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
 * 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 5
    {
46
        return $this->namespace . ':' . $aid;
47 5
    }
48
49
    /**
50
     * @inheritdoc
51
     */
52
    public function save(AuthCodeModelInterface $authCode, $attributes)
53 5
    {
54
        if ($authCode->getIsNewRecord()) {
55 5
            $result = $this->insert($authCode, $attributes);
56 5
        } else {
57 5
            $result = $this->update($authCode, $attributes);
58 1
        }
59
        return $result;
60 5
    }
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 5
    {
74
        $result = false;
75 5
        if (!$authCode->beforeSave(true)) {
76 5
            return $result;
77
        }
78
        $authCodeKey = $this->getAuthCodeKey($authCode->getKey());
79 5
        //check if record exists
80
        $entityStatus = (int)$this->db->executeCommand('EXISTS', [$authCodeKey]);
81 5
        if ($entityStatus === 1) {
82 5
            throw new DuplicateKeyException('Duplicate key "'.$authCodeKey.'"');
83 1
        }
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 5
        $redisParameters = [$authCodeKey];
87 5
        $this->setAttributesDefinitions($authCode->attributesDefinition());
88 5
        $expire = null;
89 5
        foreach ($values as $key => $value)
90 5
        {
91
            if ($key === 'expiry') {
92 5
                $expire = $value;
93 5
            }
94 5
            if ($value !== null) {
95 5
                $redisParameters[] = $key;
96 5
                $redisParameters[] = $this->convertToDatabase($key, $value);
97 5
            }
98 5
        }
99 5
        //TODO: use EXEC/MULTI to avoid errors
100
        $transaction = $this->db->executeCommand('MULTI');
101 5
        if ($transaction === true) {
102 5
            try {
103
                $this->db->executeCommand('HMSET', $redisParameters);
104 5
                if ($expire !== null) {
105 5
                    $this->db->executeCommand('EXPIREAT', [$authCodeKey, $expire]);
106 5
                }
107 5
                $this->db->executeCommand('EXEC');
108 5
            } catch (DatabaseException $e) {
109 5
                // @codeCoverageIgnoreStart
110 5
                // we have a REDIS exception, we should not discard
111 5
                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 5
        $authCode->afterSave(true, $changedAttributes);
119 5
        $result = true;
120 5
        return $result;
121 5
    }
122 5
123 5
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 1
            return false;
137
        }
138 1
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 1
        $authCodeKey = $this->getAuthCodeKey($authCodeId);
143 1
144 1
145 1
        if (isset($values[$modelKey]) === true) {
146
            $newAuthCodeKey = $this->getAuthCodeKey($values[$modelKey]);
147
            $entityStatus = (int)$this->db->executeCommand('EXISTS', [$newAuthCodeKey]);
148 1
            if ($entityStatus === 1) {
149 1
                throw new DuplicateKeyException('Duplicate key "'.$newAuthCodeKey.'"');
150 1
            }
151 1
        }
152 1
153
        $this->db->executeCommand('MULTI');
154 1
        try {
155
            if (array_key_exists($modelKey, $values) === true) {
156 1
                $oldId = $authCode->getOldKey();
157
                $oldAuthCodeKey = $this->getAuthCodeKey($oldId);
158 1
159 1
                $this->db->executeCommand('RENAMENX', [$oldAuthCodeKey, $authCodeKey]);
160 1
            }
161
162 1
            $redisUpdateParameters = [$authCodeKey];
163 1
            $redisDeleteParameters = [$authCodeKey];
164
            $this->setAttributesDefinitions($authCode->attributesDefinition());
165 1
            $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 1
            foreach ($values as $key => $value)
167 1
            {
168 1
                if ($value === null) {
169 1
                    if ($key === 'expiry') {
170
                        $expire = false;
171 1
                    }
172 1
                    $redisDeleteParameters[] = $key;
173
                } else {
174
                    if (($key === 'expiry') && ($value > 0)) {
175 1
                        $expire = $value;
176 1
                    }
177 1
                    $redisUpdateParameters[] = $key;
178
                    $redisUpdateParameters[] = $this->convertToDatabase($key, $value);
179
                }
180 1
            }
181 1
            if (count($redisDeleteParameters) > 1) {
182
                $this->db->executeCommand('HDEL', $redisDeleteParameters);
183 1
            }
184 1
            if (count($redisUpdateParameters) > 1) {
185 1
                $this->db->executeCommand('HMSET', $redisUpdateParameters);
186 1
            }
187 1
            if ($expire === false) {
188 1
                $this->db->executeCommand('PERSIST', [$authCodeKey]);
189 1
            } elseif ($expire > 0) {
190 1
                $this->db->executeCommand('EXPIREAT', [$authCodeKey, $expire]);
191
            }
192 1
193
            $this->db->executeCommand('EXEC');
194
        } catch (DatabaseException $e) {
195
            // @codeCoverageIgnoreStart
196 1
            // we have a REDIS exception, we should not discard
197 1
            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 1
            $changedAttributes[$name] = isset($oldAttributes[$name]) ? $oldAttributes[$name] : null;
206 1
            $authCode->setOldAttribute($name, $value);
207 1
        }
208 1
        $authCode->afterSave(false, $changedAttributes);
209 1
        return true;
210 1
    }
211 1
212 1
    /**
213
     * @inheritdoc
214
     */
215
    public function findOne($key)
216
    {
217
        $record = null;
218 4
        $authCodeKey = $this->getAuthCodeKey($key);
219
        $authCodeExists = (bool)$this->db->executeCommand('EXISTS', [$authCodeKey]);
220 4
        if ($authCodeExists === true) {
221 4
            $authCodeData = $this->db->executeCommand('HGETALL', [$authCodeKey]);
222 4
            $record = Yii::createObject('sweelix\oauth2\server\interfaces\AuthCodeModelInterface');
223 4
            /** @var AuthCodeModelInterface $record */
224 4
            $properties = $record->attributesDefinition();
225 4
            $this->setAttributesDefinitions($properties);
226
            $attributes = [];
227 4
            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 4
                if (isset($properties[$authCodeData[$i]]) === true) {
229 4
                    $authCodeData[$i + 1] = $this->convertToModel($authCodeData[$i], $authCodeData[($i + 1)]);
230 4
                    $record->setAttribute($authCodeData[$i], $authCodeData[$i + 1]);
231 4
                    $attributes[$authCodeData[$i]] = $authCodeData[$i + 1];
232 4
                // @codeCoverageIgnoreStart
233 4
                } elseif ($record->canSetProperty($authCodeData[$i])) {
234 4
                    // 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 4
            }
242 4
            $record->afterFind();
243 4
        }
244 4
        return $record;
245 4
    }
246 4
247 4
    /**
248
     * @inheritdoc
249
     */
250
    public function delete(AuthCodeModelInterface $authCode)
251
    {
252
        $result = false;
253 3
        if ($authCode->beforeDelete()) {
254
            $this->db->executeCommand('MULTI');
255 3
            $id = $authCode->getOldKey();
256 3
            $authCodeKey = $this->getAuthCodeKey($id);
257 3
258 3
            $this->db->executeCommand('DEL', [$authCodeKey]);
259 3
            //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 3
            $authCode->setIsNewRecord(true);
262
            $authCode->afterDelete();
263 3
            $result = true;
264 3
        }
265 3
        return $result;
266 3
    }
267
}
268