Passed
Push — devel-3.0 ( 543c48...5b8639 )
by Rubén
03:28
created

AccountHistoryRepository::deleteByAccountIdBatch()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * sysPass
4
 *
5
 * @author    nuxsmin
6
 * @link      https://syspass.org
7
 * @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
8
 *
9
 * This file is part of sysPass.
10
 *
11
 * sysPass is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation, either version 3 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * sysPass is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 *  along with sysPass.  If not, see <http://www.gnu.org/licenses/>.
23
 */
24
25
namespace SP\Repositories\Account;
26
27
use SP\Core\Exceptions\ConstraintException;
28
use SP\Core\Exceptions\QueryException;
29
use SP\Core\Exceptions\SPException;
30
use SP\DataModel\AccountHistoryData;
31
use SP\DataModel\Dto\AccountHistoryCreateDto;
32
use SP\DataModel\ItemSearchData;
33
use SP\Repositories\Repository;
34
use SP\Repositories\RepositoryItemInterface;
35
use SP\Repositories\RepositoryItemTrait;
36
use SP\Services\Account\AccountPasswordRequest;
37
use SP\Storage\Database\QueryData;
38
use SP\Storage\Database\QueryResult;
39
40
/**
41
 * Class AccountHistoryRepository
42
 *
43
 * @package Services
44
 */
45
final class AccountHistoryRepository extends Repository implements RepositoryItemInterface
46
{
47
    use RepositoryItemTrait;
48
49
    /**
50
     * Obtiene el listado del histórico de una cuenta.
51
     *
52
     * @param $id
53
     *
54
     * @return QueryResult
55
     * @throws QueryException
56
     * @throws ConstraintException
57
     */
58
    public function getHistoryForAccount($id)
59
    {
60
        $query = /** @lang SQL */
61
            'SELECT AH.id,
62
            AH.dateEdit,
63
            AH.dateAdd ,
64
            U1.login AS userAdd,
65
            U2.login AS userEdit
66
            FROM AccountHistory AH
67
            INNER JOIN User U1 ON AH.userId = U1.id
68
            LEFT JOIN User U2 ON AH.userEditId = U2.id
69
            WHERE AH.accountId = ?
70
            ORDER BY AH.id DESC';
71
72
        $queryData = new QueryData();
73
        $queryData->setQuery($query);
74
        $queryData->addParam($id);
75
76
        return $this->db->doSelect($queryData);
77
    }
78
79
    /**
80
     * Crea una nueva cuenta en la BBDD
81
     *
82
     * @param AccountHistoryCreateDto $dto
83
     *
84
     * @return int
85
     * @throws QueryException
86
     * @throws ConstraintException
87
     */
88
    public function create($dto)
89
    {
90
        $queryData = new QueryData();
91
        $query = /** @lang SQL */
92
            'INSERT INTO AccountHistory
93
            (accountId,
94
            categoryId,
95
            clientId,
96
            `name`,
97
            login,
98
            url,
99
            pass,
100
            `key`,
101
            notes,
102
            countView,
103
            countDecrypt,
104
            dateAdd,
105
            dateEdit,
106
            userId,
107
            userGroupId,
108
            userEditId,
109
            otherUserEdit,
110
            otherUserGroupEdit,
111
            isPrivate,
112
            isPrivateGroup,
113
            isModify,
114
            isDeleted,
115
            mPassHash)
116
            SELECT id,
117
            categoryId,
118
            clientId,
119
            `name`,
120
            login,
121
            url,
122
            pass,
123
            `key`,
124
            notes,
125
            countView,
126
            countDecrypt,
127
            dateAdd,
128
            dateEdit,
129
            userId,
130
            userGroupId,
131
            userEditId,
132
            otherUserEdit,
133
            otherUserGroupEdit,
134
            isPrivate,
135
            isPrivateGroup,
136
            ?,?,? FROM Account WHERE id = ?';
137
138
        $queryData->setQuery($query);
139
        $queryData->addParam((int)$dto->isModify());
140
        $queryData->addParam((int)$dto->isDelete());
141
        $queryData->addParam($dto->getMasterPassHash());
142
        $queryData->addParam($dto->getAccountId());
143
        $queryData->setOnErrorMessage(__u('Error al actualizar el historial'));
144
145
        return $this->db->doQuery($queryData)->getLastId();
146
    }
147
148
    /**
149
     * Elimina los datos de una cuenta en la BBDD.
150
     *
151
     * @param int $id
152
     *
153
     * @return bool Los ids de las cuentas eliminadas
154
     * @throws ConstraintException
155
     * @throws QueryException
156
     */
157
    public function delete($id)
158
    {
159
        $queryData = new QueryData();
160
        $queryData->setQuery('DELETE FROM AccountHistory WHERE id = ? LIMIT 1');
161
        $queryData->addParam($id);
162
        $queryData->setOnErrorMessage(__u('Error al eliminar la cuenta'));
163
164
        return $this->db->doQuery($queryData)->getAffectedNumRows();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->db->doQuer...)->getAffectedNumRows() returns the type integer which is incompatible with the documented return type boolean.
Loading history...
165
    }
166
167
    /**
168
     * Updates an item
169
     *
170
     * @param mixed $itemData
171
     *
172
     * @return mixed
173
     */
174
    public function update($itemData)
175
    {
176
        throw new \RuntimeException('Not implemented');
177
    }
178
179
    /**
180
     * Returns the item for given id
181
     *
182
     * @param int $id
183
     *
184
     * @return QueryResult
185
     * @throws SPException
186
     */
187
    public function getById($id)
188
    {
189
        $query = /** @lang SQL */
190
            'SELECT AH.id,
191
            AH.accountId,
192
            AH.clientId,
193
            AH.categoryId,
194
            AH.name,
195
            AH.login,
196
            AH.url,
197
            AH.pass,
198
            AH.key,
199
            AH.notes,
200
            AH.countView,
201
            AH.countDecrypt,
202
            AH.dateAdd,
203
            AH.dateEdit,
204
            AH.userId,
205
            AH.userGroupId,
206
            AH.userEditId,
207
            AH.isModify,
208
            AH.isDeleted,
209
            AH.otherUserEdit,
210
            AH.otherUserGroupEdit,
211
            AH.isPrivate,
212
            AH.isPrivateGroup,
213
            U1.name AS userName,
214
            U1.login AS userLogin,
215
            UG.name AS userGroupName,
216
            U2.name AS userEditName,
217
            U2.login AS userEditLogin,
218
            C.name AS categoryName,
219
            C2.name AS clientName
220
            FROM AccountHistory AH
221
            INNER JOIN Category C ON AH.categoryId = C.id
222
            INNER JOIN Client C2 ON AH.clientId = C2.id
223
            INNER JOIN UserGroup UG ON AH.userGroupId = UG.id
224
            INNER JOIN User U1 ON AH.userId = U1.id
225
            LEFT JOIN User U2 ON AH.userEditId = U2.id
226
            WHERE AH.id = ? LIMIT 1';
227
228
        $queryData = new QueryData();
229
        $queryData->setQuery($query);
230
        $queryData->setMapClassName(AccountHistoryData::class);
231
        $queryData->addParam($id);
232
233
        return $this->db->doSelect($queryData);
234
    }
235
236
    /**
237
     * Returns all the items
238
     *
239
     * @return QueryResult
240
     * @throws QueryException
241
     * @throws ConstraintException
242
     */
243
    public function getAll()
244
    {
245
        $query = /** @lang SQL */
246
            'SELECT AH.id,
247
            AH.dateEdit,
248
            AH.dateAdd, 
249
            U1.login AS userAdd,
250
            U2.login AS userEdit
251
            FROM AccountHistory AH
252
            INNER JOIN User U1 ON AH.userId = U1.id 
253
            LEFT JOIN User U2 ON AH.userEditId = U2.id 
254
            ORDER BY AH.id DESC';
255
256
        $queryData = new QueryData();
257
        $queryData->setQuery($query);
258
259
        return $this->db->doSelect($queryData);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->db->doSelect($queryData) returns the type SP\Storage\Database\QueryResult which is incompatible with the return type mandated by SP\Repositories\RepositoryItemInterface::getAll() of array.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
260
    }
261
262
    /**
263
     * Returns all the items for given ids
264
     *
265
     * @param array $ids
266
     *
267
     * @return void
268
     */
269
    public function getByIdBatch(array $ids)
270
    {
271
        throw new \RuntimeException('Not implemented');
272
    }
273
274
    /**
275
     * Deletes all the items for given ids
276
     *
277
     * @param array $ids
278
     *
279
     * @return int
280
     * @throws ConstraintException
281
     * @throws QueryException
282
     */
283
    public function deleteByIdBatch(array $ids)
284
    {
285
        if (empty($ids)) {
286
            return 0;
0 ignored issues
show
Bug Best Practice introduced by
The expression return 0 returns the type integer which is incompatible with the return type mandated by SP\Repositories\Reposito...face::deleteByIdBatch() of SP\Repositories\RepositoryItemInterface.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
287
        }
288
289
        $queryData = new QueryData();
290
        $queryData->setQuery('DELETE FROM AccountHistory WHERE id IN (' . $this->getParamsFromArray($ids) . ')');
291
        $queryData->setParams($ids);
292
        $queryData->setOnErrorMessage(__u('Error al eliminar las cuentas'));
293
294
        return $this->db->doQuery($queryData)->getAffectedNumRows();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->db->doQuer...)->getAffectedNumRows() returns the type integer which is incompatible with the return type mandated by SP\Repositories\Reposito...face::deleteByIdBatch() of SP\Repositories\RepositoryItemInterface.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
295
    }
296
297
    /**
298
     * Deletes all the items for given accounts id
299
     *
300
     * @param array $ids
301
     *
302
     * @return int
303
     * @throws ConstraintException
304
     * @throws QueryException
305
     */
306
    public function deleteByAccountIdBatch(array $ids)
307
    {
308
        if (empty($ids)) {
309
            return 0;
310
        }
311
312
        $queryData = new QueryData();
313
        $queryData->setQuery('DELETE FROM AccountHistory WHERE accountId IN (' . $this->getParamsFromArray($ids) . ')');
314
        $queryData->setParams($ids);
315
        $queryData->setOnErrorMessage(__u('Error al eliminar las cuentas'));
316
317
        return $this->db->doQuery($queryData)->getAffectedNumRows();
318
    }
319
320
    /**
321
     * Checks whether the item is in use or not
322
     *
323
     * @param $id int
324
     *
325
     * @return void
326
     */
327
    public function checkInUse($id)
328
    {
329
        throw new \RuntimeException('Not implemented');
330
    }
331
332
    /**
333
     * Checks whether the item is duplicated on updating
334
     *
335
     * @param mixed $itemData
336
     *
337
     * @return void
338
     */
339
    public function checkDuplicatedOnUpdate($itemData)
340
    {
341
        throw new \RuntimeException('Not implemented');
342
    }
343
344
    /**
345
     * Checks whether the item is duplicated on adding
346
     *
347
     * @param mixed $itemData
348
     *
349
     * @return void
350
     */
351
    public function checkDuplicatedOnAdd($itemData)
352
    {
353
        throw new \RuntimeException('Not implemented');
354
    }
355
356
    /**
357
     * Searches for items by a given filter
358
     *
359
     * @param ItemSearchData $itemSearchData
360
     *
361
     * @return QueryResult
362
     * @throws ConstraintException
363
     * @throws QueryException
364
     */
365
    public function search(ItemSearchData $itemSearchData)
366
    {
367
        $queryData = new QueryData();
368
        $queryData->setSelect('AH.id, AH.name, C.name as clientName, C2.name as categoryName, IFNULL(AH.dateEdit,AH.dateAdd) as date, AH.isModify, AH.isDeleted');
369
        $queryData->setFrom('AccountHistory AH 
370
        INNER JOIN Client C ON AH.clientId = C.id
371
        INNER JOIN Category C2 ON AH.categoryId = C2.id
372
        ');
373
        $queryData->setOrder('date DESC, AH.name, C.name, AH.id DESC');
374
375
        if ($itemSearchData->getSeachString() !== '') {
376
            $queryData->setWhere('AH.name LIKE ? OR C.name LIKE ?');
377
378
            $search = '%' . $itemSearchData->getSeachString() . '%';
379
            $queryData->addParam($search);
380
            $queryData->addParam($search);
381
        }
382
383
        $queryData->setLimit('?,?');
384
        $queryData->addParam($itemSearchData->getLimitStart());
385
        $queryData->addParam($itemSearchData->getLimitCount());
386
387
        return $this->db->doSelect($queryData, true);
388
    }
389
390
    /**
391
     * Obtener los datos relativos a la clave de todas las cuentas.
392
     *
393
     * @return QueryResult
394
     * @throws ConstraintException
395
     * @throws QueryException
396
     */
397
    public function getAccountsPassData()
398
    {
399
        $query = /** @lang SQL */
400
            'SELECT id, `name`, pass, `key`, mPassHash
401
            FROM AccountHistory WHERE BIT_LENGTH(pass) > 0
402
            ORDER BY id';
403
404
        $queryData = new QueryData();
405
        $queryData->setQuery($query);
406
407
        return $this->db->doSelect($queryData);
408
    }
409
410
    /**
411
     * Actualiza la clave de una cuenta en la BBDD.
412
     *
413
     * @param AccountPasswordRequest $request
414
     *
415
     * @return bool
416
     * @throws ConstraintException
417
     * @throws QueryException
418
     */
419
    public function updatePassword(AccountPasswordRequest $request)
420
    {
421
        $query = /** @lang SQL */
422
            'UPDATE AccountHistory SET 
423
            pass = ?,
424
            `key` = ?,
425
            mPassHash = ?
426
            WHERE id = ?';
427
428
        $queryData = new QueryData();
429
        $queryData->setQuery($query);
430
        $queryData->setParams([
431
            $request->pass,
432
            $request->key,
433
            $request->hash,
434
            $request->id
435
        ]);
436
        $queryData->setOnErrorMessage(__u('Error al actualizar la clave'));
437
438
        return $this->db->doQuery($queryData)->getAffectedNumRows();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->db->doQuer...)->getAffectedNumRows() returns the type integer which is incompatible with the documented return type boolean.
Loading history...
439
    }
440
}