CypherKeyService   A
last analyzed

Complexity

Total Complexity 31

Size/Duplication

Total Lines 214
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 31
c 0
b 0
f 0
lcom 1
cbo 5
dl 0
loc 214
rs 9.92

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getCypherKeyKey() 0 4 1
A save() 0 9 2
B insert() 0 43 7
F update() 0 66 13
B findOne() 0 31 6
A delete() 0 17 2
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
    protected function getCypherKeyKey($aid)
46
    {
47
        return $this->namespace . ':' . $aid;
48
    }
49
50
    /**
51
     * @inheritdoc
52
     */
53
    public function save(CypherKeyModelInterface $cypherKey, $attributes)
54
    {
55
        if ($cypherKey->getIsNewRecord()) {
56
            $result = $this->insert($cypherKey, $attributes);
57
        } else {
58
            $result = $this->update($cypherKey, $attributes);
59
        }
60
        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
    protected function insert(CypherKeyModelInterface $cypherKey, $attributes)
74
    {
75
        $result = false;
76
        if (!$cypherKey->beforeSave(true)) {
77
            return $result;
78
        }
79
        $cypherKeyKey = $this->getCypherKeyKey($cypherKey->getKey());
80
        //check if record exists
81
        $entityStatus = (int)$this->db->executeCommand('EXISTS', [$cypherKeyKey]);
82
        if ($entityStatus === 1) {
83
            throw new DuplicateKeyException('Duplicate key "'.$cypherKeyKey.'"');
84
        }
85
86
        $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
        $redisParameters = [$cypherKeyKey];
88
        $this->setAttributesDefinitions($cypherKey->attributesDefinition());
89
        foreach ($values as $key => $value)
90
        {
91
            if ($value !== null) {
92
                $redisParameters[] = $key;
93
                $redisParameters[] = $this->convertToDatabase($key, $value);
94
            }
95
        }
96
        //TODO: use EXEC/MULTI to avoid errors
97
        $transaction = $this->db->executeCommand('MULTI');
98
        if ($transaction === true) {
99
            try {
100
                $this->db->executeCommand('HMSET', $redisParameters);
101
                $this->db->executeCommand('EXEC');
102
            } 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
        }
110
        $changedAttributes = array_fill_keys(array_keys($values), null);
111
        $cypherKey->setOldAttributes($values);
112
        $cypherKey->afterSave(true, $changedAttributes);
113
        $result = true;
114
        return $result;
115
    }
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
    protected function update(CypherKeyModelInterface $cypherKey, $attributes)
128
    {
129
        if (!$cypherKey->beforeSave(false)) {
130
            return false;
131
        }
132
133
        $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
        $modelKey = $cypherKey->key();
135
        $cypherKeyId = isset($values[$modelKey]) ? $values[$modelKey] : $cypherKey->getKey();
136
        $cypherKeyKey = $this->getCypherKeyKey($cypherKeyId);
137
138
139
        if (isset($values[$modelKey]) === true) {
140
            $newCypherKeyKey = $this->getCypherKeyKey($values[$modelKey]);
141
            $entityStatus = (int)$this->db->executeCommand('EXISTS', [$newCypherKeyKey]);
142
            if ($entityStatus === 1) {
143
                throw new DuplicateKeyException('Duplicate key "'.$newCypherKeyKey.'"');
144
            }
145
        }
146
147
        $this->db->executeCommand('MULTI');
148
        try {
149
            if (array_key_exists($modelKey, $values) === true) {
150
                $oldId = $cypherKey->getOldKey();
151
                $oldCypherKeyKey = $this->getCypherKeyKey($oldId);
152
153
                $this->db->executeCommand('RENAMENX', [$oldCypherKeyKey, $cypherKeyKey]);
154
            }
155
156
            $redisUpdateParameters = [$cypherKeyKey];
157
            $redisDeleteParameters = [$cypherKeyKey];
158
            $this->setAttributesDefinitions($cypherKey->attributesDefinition());
159
            foreach ($values as $key => $value)
160
            {
161
                if ($value === null) {
162
                    $redisDeleteParameters[] = $key;
163
                } else {
164
                    $redisUpdateParameters[] = $key;
165
                    $redisUpdateParameters[] = $this->convertToDatabase($key, $value);
166
                }
167
            }
168
            if (count($redisDeleteParameters) > 1) {
169
                $this->db->executeCommand('HDEL', $redisDeleteParameters);
170
            }
171
            if (count($redisUpdateParameters) > 1) {
172
                $this->db->executeCommand('HMSET', $redisUpdateParameters);
173
            }
174
175
            $this->db->executeCommand('EXEC');
176
        } 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
        $changedAttributes = [];
185
        foreach ($values as $name => $value) {
186
            $oldAttributes = $cypherKey->getOldAttributes();
187
            $changedAttributes[$name] = isset($oldAttributes[$name]) ? $oldAttributes[$name] : null;
188
            $cypherKey->setOldAttribute($name, $value);
189
        }
190
        $cypherKey->afterSave(false, $changedAttributes);
191
        return true;
192
    }
193
194
    /**
195
     * @inheritdoc
196
     */
197
    public function findOne($key)
198
    {
199
        $record = null;
200
        $cypherKeyKey = $this->getCypherKeyKey($key);
201
        $cypherKeyExists = (bool)$this->db->executeCommand('EXISTS', [$cypherKeyKey]);
202
        if ($cypherKeyExists === true) {
203
            $cypherKeyData = $this->db->executeCommand('HGETALL', [$cypherKeyKey]);
204
            $record = Yii::createObject(CypherKeyModelInterface::class);
205
            /** @var CypherKeyModelInterface $record */
206
            $properties = $record->attributesDefinition();
207
            $this->setAttributesDefinitions($properties);
208
            $attributes = [];
209
            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
                if (isset($properties[$cypherKeyData[$i]]) === true) {
211
                    $cypherKeyData[$i + 1] = $this->convertToModel($cypherKeyData[$i], $cypherKeyData[($i + 1)]);
212
                    $record->setAttribute($cypherKeyData[$i], $cypherKeyData[$i + 1]);
213
                    $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
            }
221
            if (empty($attributes) === false) {
222
                $record->setOldAttributes($attributes);
223
            }
224
            $record->afterFind();
225
        }
226
        return $record;
227
    }
228
229
    /**
230
     * @inheritdoc
231
     */
232
    public function delete(CypherKeyModelInterface $cypherKey)
233
    {
234
        $result = false;
235
        if ($cypherKey->beforeDelete()) {
236
            $this->db->executeCommand('MULTI');
237
            $id = $cypherKey->getOldKey();
238
            $cypherKeyKey = $this->getCypherKeyKey($id);
239
240
            $this->db->executeCommand('DEL', [$cypherKeyKey]);
241
            //TODO: check results to return correct information
242
            $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
            $cypherKey->setIsNewRecord(true);
244
            $cypherKey->afterDelete();
245
            $result = true;
246
        }
247
        return $result;
248
    }
249
250
}
251