Completed
Push — devel ( f78bd1...13d8c8 )
by Philippe
11s
created

CypherKeyService::insert()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

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