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

JwtService::insert()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 41
rs 8.6417
cc 6
nc 8
nop 2
1
<?php
2
/**
3
 * JwtService.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\JwtModelInterface;
20
use sweelix\oauth2\server\interfaces\JwtServiceInterface;
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 jwt service for mySql
29
 *  database structure
30
 *    * oauth2:jwt:<jid> : hash (Jwt)
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 JwtService extends BaseService implements JwtServiceInterface
41
{
42
    /**
43
     * @var string sql jwts table
44
     */
45
    public $jwtsTable = null;
46
47
    /**
48
     * Save Jwt
49
     * @param JwtModelInterface $jwt
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(JwtModelInterface $jwt, $attributes)
58
    {
59
        $result = false;
60
        if (!$jwt->beforeSave(true)) {
61
            return $result;
62
        }
63
        $entity = (new Query())
64
            ->select('*')
65
            ->from($this->jwtsTable)
66
            ->where('id = :id', [':id' => $jwt->id])
0 ignored issues
show
Bug introduced by
Accessing id on the interface sweelix\oauth2\server\interfaces\JwtModelInterface 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...
67
            ->one($this->db);
68
        if ($entity !== false) {
69
            throw new DuplicateKeyException('Duplicate key "' . $jwt->id . '"');
0 ignored issues
show
Bug introduced by
Accessing id on the interface sweelix\oauth2\server\interfaces\JwtModelInterface 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...
70
        }
71
        $values = $jwt->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...
72
        $jwtParameters = [];
73
        $this->setAttributesDefinitions($jwt->attributesDefinition());
74
        foreach ($values as $key => $value) {
75
            if ($value !== null) {
76
                $jwtParameters[$key] = $this->convertToDatabase($key, $value);
77
            }
78
        }
79
        $jwtParameters['dateCreated'] = new Expression('NOW()');
80
        $jwtParameters['dateUpdated'] = new Expression('NOW()');
81
        try {
82
            $this->db->createCommand()
83
                ->insert($this->jwtsTable, $jwtParameters)
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
        $jwt->setOldAttributes($values);
94
        $jwt->afterSave(true, $changedAttributes);
95
        $result = true;
96
        return $result;
97
    }
98
99
    /**
100
     * Update Jwt
101
     * @param JwtModelInterface $jwt
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(JwtModelInterface $jwt, $attributes)
109
    {
110
        if (!$jwt->beforeSave(false)) {
111
            return false;
112
        }
113
114
        $values = $jwt->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 = $jwt->key();
116
        if (isset($values[$modelKey]) === true) {
117
            $entity = (new Query())
118
                ->select('*')
119
                ->from($this->jwtsTable)
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
        $jwtKey = isset($values[$modelKey]) ? $values[$modelKey] : $jwt->getKey();
127
128
        $jwtParameters = [];
129
        $this->setAttributesDefinitions($jwt->attributesDefinition());
130
        foreach ($values as $key => $value) {
131
            $jwtParameters[$key] = ($value !== null) ? $this->convertToDatabase($key, $value) : null;
132
        }
133
        $jwtParameters['dateUpdated'] = new Expression('NOW()');
134
        try {
135
            if (array_key_exists($modelKey, $values) === true) {
136
                $oldJwtKey = $jwt->getOldKey();
137
                $this->db->createCommand()
138
                    ->update($this->jwtsTable, $jwtParameters, 'id = :id', [':id' => $oldJwtKey])
139
                    ->execute();
140
            } else {
141
                $this->db->createCommand()
142
                    ->update($this->jwtsTable, $jwtParameters, 'id = :id', [':id' => $jwtKey])
143
                    ->execute();
144
            }
145
        } catch (DatabaseException $e) {
146
            // @codeCoverageIgnoreStart
147
            // we have a MYSQL exception, we should not discard
148
            Yii::debug('Error while updating entity', __METHOD__);
149
            throw $e;
150
            // @codeCoverageIgnoreEnd
151
        }
152
153
        $changedAttributes = [];
154
        foreach ($values as $name => $value) {
155
            $oldAttributes = $jwt->getOldAttributes();
156
            $changedAttributes[$name] = isset($oldAttributes[$name]) ? $oldAttributes[$name] : null;
157
            $jwt->setOldAttribute($name, $value);
158
        }
159
        $jwt->afterSave(false, $changedAttributes);
160
        return true;
161
    }
162
163
    /**
164
     * @inheritdoc
165
     */
166
    public function save(JwtModelInterface $jwt, $attributes)
167
    {
168
        if ($jwt->getIsNewRecord()) {
169
            $result = $this->insert($jwt, $attributes);
170
        } else {
171
            $result = $this->update($jwt, $attributes);
172
        }
173
        return $result;
174
    }
175
176
    /**
177
     * @inheritdoc
178
     */
179
    public function findOne($key)
180
    {
181
        $record = null;
182
        $jwtData = (new Query())
183
            ->select('*')
184
            ->from($this->jwtsTable)
185
            ->where('id = :id', [':id' => $key])
186
            ->one($this->db);
187
        if ($jwtData !== false) {
188
            $record = Yii::createObject('sweelix\oauth2\server\interfaces\JwtModelInterface');
189
            /** @var JwtModelInterface $record */
190
            $properties = $record->attributesDefinition();
191
            $this->setAttributesDefinitions($properties);
192
            $attributes = [];
193
            foreach ($jwtData as $key => $value) {
194
                if (isset($properties[$key]) === true) {
195
                    $jwtData[$key] = $this->convertToModel($key, $value);
196
                    $record->setAttribute($key, $jwtData[$key]);
197
                    $attributes[$key] = $jwtData[$key];
198
                    // @codeCoverageIgnoreStart
199
                } elseif ($record->canSetProperty($key)) {
200
                    // TODO: find a way to test attribute population
201
                    $record->{$key} = $value;
202
                }
203
                // @codeCoverageIgnoreEnd
204
            }
205
            if (empty($attributes) === false) {
206
                $record->setOldAttributes($attributes);
207
            }
208
            $record->afterFind();
209
        }
210
        return $record;
211
    }
212
213
    /**
214
     * @inheritdoc
215
     */
216
    public function delete(JwtModelInterface $jwt)
217
    {
218
        $result = false;
219
        if ($jwt->beforeDelete()) {
220
            //TODO: check results to return correct information
221
            $this->db->createCommand()
222
                ->delete($this->jwtsTable, 'id = :id', [':id' => $jwt->getKey()])
223
                ->execute();
224
            $jwt->setIsNewRecord(true);
225
            $jwt->afterDelete();
226
            $result = true;
227
        }
228
        return $result;
229
    }
230
}