Completed
Pull Request — devel (#18)
by
unknown
61:36 queued 21:23
created

JtiService::update()   C

Complexity

Conditions 11
Paths 122

Size

Total Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

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