CypherKeyService::update()   F
last analyzed

Complexity

Conditions 13
Paths 627

Size

Total Lines 66

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 40
CRAP Score 13.2317

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 66
ccs 40
cts 45
cp 0.8889
rs 3.1162
cc 13
nc 627
nop 2
crap 13.2317

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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