Completed
Pull Request — devel (#18)
by
unknown
38:28
created

CypherKeyService::update()   C

Complexity

Conditions 12
Paths 162

Size

Total Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 56
rs 6.12
cc 12
nc 162
nop 2

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\mySql
13
 */
14
15
namespace sweelix\oauth2\server\services\mySql;
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
use yii\db\Expression;
24
use yii\db\Query;
25
26
/**
27
 * This is the cypher key service for mySql
28
 *  database structure
29
 *    * oauth2:cypherKeys:<aid> : hash (CypherKey)
30
 *
31
 * @author Philippe Gaultier <[email protected]>
32
 * @copyright 2010-2017 Philippe Gaultier
33
 * @license http://www.sweelix.net/license license
34
 * @version 1.2.0
35
 * @link http://www.sweelix.net
36
 * @package sweelix\oauth2\server\services\mySql
37
 * @since 1.0.0
38
 */
39
class CypherKeyService extends BaseService implements CypherKeyServiceInterface
40
{
41
    /**
42
     * @var string sql cypherKeys tables
43
     */
44
    public $cypherKeysTable = null;
45
46
    /**
47
     * Save Cypher Key
48
     * @param CypherKeyModelInterface $cypherKey
49
     * @param null|array $attributes attributes to save
50
     * @return bool
51
     * @throws DatabaseException
52
     * @throws DuplicateIndexException
53
     * @throws DuplicateKeyException
54
     * @since 1.0.0
55
     */
56
    protected function insert(CypherKeyModelInterface $cypherKey, $attributes)
57
    {
58
        $result = false;
59
        if (!$cypherKey->beforeSave(true)) {
60
            return $result;
61
        }
62
        $cypherKeyKey = $cypherKey->getKey();
63
        $entity = (new Query())
64
            ->select('*')
65
            ->from($this->cypherKeysTable)
66
            ->where('id = :id', [':id' => $cypherKeyKey])
67
            ->one($this->db);
68
        if ($entity !== false) {
69
            throw new DuplicateKeyException('Duplicate key "' . $cypherKeyKey . '"');
70
        }
71
        $values = $cypherKey->getDirtyAttributes($attributes);
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 56 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...
72
        $cypherKeyParameters = [];
73
        $this->setAttributesDefinitions($cypherKey->attributesDefinition());
74
        foreach ($values as $key => $value) {
75
            if ($value !== null) {
76
                $cypherKeyParameters[$key] = $this->convertToDatabase($key, $value);
77
            }
78
        }
79
        $cypherKeyParameters['dateCreated'] = new Expression('NOW()');
80
        $cypherKeyParameters['dateUpdated'] = new Expression('NOW()');
81
        try {
82
            $this->db->createCommand()
83
                ->insert($this->cypherKeysTable, $cypherKeyParameters)
84
                ->execute();
85
        } catch (DatabaseException $e) {
86
            // @codeCoverageIgnoreStart
87
            // we have a MYSQL exception, we should not discard
88
            Yii::debug('Error while inserting entity', __METHOD__);
89
            throw $e;
90
            // @codeCoverageIgnoreEnd
91
        }
92
        $changedAttributes = array_fill_keys(array_keys($values), null);
93
        $cypherKey->setOldAttributes($values);
94
        $cypherKey->afterSave(true, $changedAttributes);
95
        $result = true;
96
        return $result;
97
    }
98
99
    /**
100
     * Update Cypher Key
101
     * @param CypherKeyModelInterface $cypherKey
102
     * @param null|array $attributes attributes to save
103
     * @return bool
104
     * @throws DatabaseException
105
     * @throws DuplicateIndexException
106
     * @throws DuplicateKeyException
107
     */
108
    protected function update(CypherKeyModelInterface $cypherKey, $attributes)
109
    {
110
        if (!$cypherKey->beforeSave(false)) {
111
            return false;
112
        }
113
114
        $values = $cypherKey->getDirtyAttributes($attributes);
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 108 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...
115
        $modelKey = $cypherKey->key();
116
        if (isset($values[$modelKey]) === true) {
117
            $entity = (new Query())
118
                ->select('*')
119
                ->from($this->cypherKeysTable)
120
                ->where('id = :id', [':id' => $values[$modelKey]])
121
                ->one($this->db);
122
            if ($entity !== false) {
123
                throw new DuplicateKeyException('Duplicate key "' . $values[$modelKey] . '"');
124
            }
125
        }
126
        $cypherKeyKey = isset($values[$modelKey]) ? $values[$modelKey] : $cypherKey->getKey();
127
128
        $cypherKeyParameters = [];
129
        $this->setAttributesDefinitions($cypherKey->attributesDefinition());
130
        foreach ($values as $key => $value) {
131
            if ($key !== 'scopes') {
132
                $cypherKeyParameters[$key] = ($value !== null) ? $this->convertToDatabase($key, $value) : null;
133
            }
134
        }
135
        $cypherKeyParameters['dateUpdated'] = new Expression('NOW()');
136
        try {
137
            if (array_key_exists($modelKey, $values) === true) {
138
                $oldCypherKeyKey = $cypherKey->getOldKey();
139
                $this->db->createCommand()
140
                    ->update($this->cypherKeysTable, $cypherKeyParameters, 'id = :id', [':id' => $oldCypherKeyKey])
141
                    ->execute();
142
            } else {
143
                $this->db->createCommand()
144
                    ->update($this->cypherKeysTable, $cypherKeyParameters, 'id = :id', [':id' => $cypherKeyKey])
145
                    ->execute();
146
            }
147
        } catch (DatabaseException $e) {
148
            // @codeCoverageIgnoreStart
149
            // we have a MYSQL exception, we should not discard
150
            Yii::debug('Error while updating entity', __METHOD__);
151
            throw $e;
152
            // @codeCoverageIgnoreEnd
153
        }
154
155
        $changedAttributes = [];
156
        foreach ($values as $name => $value) {
157
            $oldAttributes = $cypherKey->getOldAttributes();
158
            $changedAttributes[$name] = isset($oldAttributes[$name]) ? $oldAttributes[$name] : null;
159
            $cypherKey->setOldAttribute($name, $value);
160
        }
161
        $cypherKey->afterSave(false, $changedAttributes);
162
        return true;
163
    }
164
165
    /**
166
     * @inheritdoc
167
     */
168
    public function save(CypherKeyModelInterface $cypherKey, $attributes)
169
    {
170
        if ($cypherKey->getIsNewRecord()) {
171
            $result = $this->insert($cypherKey, $attributes);
172
        } else {
173
            $result = $this->update($cypherKey, $attributes);
174
        }
175
        return $result;
176
    }
177
178
    /**
179
     * @inheritdoc
180
     */
181
    public function findOne($key)
182
    {
183
        $record = null;
184
        $CypherKeyData = (new Query())
185
            ->select('*')
186
            ->from($this->cypherKeysTable)
187
            ->where('id = :id', [':id' => $key])
188
            ->one($this->db);
189
190
        if ($CypherKeyData !== false) {
191
            $record = Yii::createObject('sweelix\oauth2\server\interfaces\CypherKeyModelInterface');
192
            /** @var CypherKeyModelInterface $record */
193
            $properties = $record->attributesDefinition();
194
            $this->setAttributesDefinitions($properties);
195
            $attributes = [];
196
            foreach ($CypherKeyData as $key => $value) {
197
                if (isset($properties[$key]) === true) {
198
                    $CypherKeyData[$key] = $this->convertToModel($key, $value);
199
                    $record->setAttribute($key, $CypherKeyData[$key]);
200
                    $attributes[$key] = $CypherKeyData[$key];
201
                    // @codeCoverageIgnoreStart
202
                } elseif ($record->canSetProperty($key)) {
203
                    // TODO: find a way to test attribute population
204
                    $record->{$key} = $value;
205
                }
206
                // @codeCoverageIgnoreEnd
207
            }
208
            if (empty($attributes) === false) {
209
                $record->setOldAttributes($attributes);
210
            }
211
            $record->afterFind();
212
        }
213
        return $record;
214
    }
215
216
    /**
217
     * @inheritdoc
218
     */
219
    public function delete(CypherKeyModelInterface $cypherKey)
220
    {
221
        $result = false;
222
        if ($cypherKey->beforeDelete()) {
223
            //TODO: check results to return correct information
224
            $this->db->createCommand()
225
                ->delete($this->cypherKeysTable, 'id = :id', [':id' => $cypherKey->getKey()])
226
                ->execute();
227
            $cypherKey->setIsNewRecord(true);
228
            $cypherKey->afterDelete();
229
            $result = true;
230
        }
231
        return $result;
232
    }
233
}