Passed
Push — devel-3.0 ( e49526...a37b49 )
by Rubén
04:05
created

NotificationRepository::searchForAdmin()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 33
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 22
nc 2
nop 2
dl 0
loc 33
rs 9.568
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\Notification;
26
27
use SP\Core\Exceptions\ConstraintException;
28
use SP\Core\Exceptions\QueryException;
29
use SP\DataModel\ItemSearchData;
30
use SP\DataModel\NotificationData;
31
use SP\Mvc\Model\QueryCondition;
32
use SP\Repositories\Repository;
33
use SP\Repositories\RepositoryItemInterface;
34
use SP\Repositories\RepositoryItemTrait;
35
use SP\Storage\Database\QueryData;
36
use SP\Storage\Database\QueryResult;
37
38
/**
39
 * Class NotificationRepository
40
 *
41
 * @package SP\Repositories\Notification
42
 */
43
final class NotificationRepository extends Repository implements RepositoryItemInterface
44
{
45
    use RepositoryItemTrait;
46
47
    /**
48
     * Creates an item
49
     *
50
     * @param NotificationData $itemData
51
     *
52
     * @return QueryResult
53
     * @throws ConstraintException
54
     * @throws QueryException
55
     */
56
    public function create($itemData)
57
    {
58
        $query = /** @lang SQL */
59
            'INSERT INTO Notification 
60
            SET type = ?,
61
            component = ?,
62
            description = ?,
63
            `date` = UNIX_TIMESTAMP(),
64
            checked = 0,
65
            userId = ?,
66
            sticky = ?,
67
            onlyAdmin = ?';
68
69
        $queryData = new QueryData();
70
        $queryData->setQuery($query);
71
        $queryData->setParams([
72
            $itemData->getType(),
73
            $itemData->getComponent(),
74
            $itemData->getDescription(),
75
            $itemData->getUserId() ?: null,
76
            $itemData->isSticky(),
77
            $itemData->isOnlyAdmin()
78
        ]);
79
        $queryData->setOnErrorMessage(__u('Error al crear la notificación'));
80
81
        return $this->db->doQuery($queryData);
82
    }
83
84
    /**
85
     * Updates an item
86
     *
87
     * @param NotificationData $itemData
88
     *
89
     * @return int
90
     * @throws ConstraintException
91
     * @throws QueryException
92
     */
93
    public function update($itemData)
94
    {
95
        $query = /** @lang SQL */
96
            'UPDATE Notification 
97
            SET type = ?,
98
            component = ?,
99
            description = ?,
100
            `date` = UNIX_TIMESTAMP(),
101
            checked = ?,
102
            userId = ?,
103
            sticky = ?,
104
            onlyAdmin = ? 
105
            WHERE id = ? LIMIT 1';
106
107
        $queryData = new QueryData();
108
        $queryData->setQuery($query);
109
        $queryData->setParams([
110
            $itemData->getType(),
111
            $itemData->getComponent(),
112
            $itemData->getDescription(),
113
            $itemData->isChecked(),
114
            $itemData->getUserId() ?: null,
115
            $itemData->isSticky(),
116
            $itemData->isOnlyAdmin(),
117
            $itemData->getId()
118
        ]);
119
        $queryData->setOnErrorMessage(__u('Error al modificar la notificación'));
120
121
        return $this->db->doQuery($queryData)->getAffectedNumRows();
122
    }
123
124
    /**
125
     * Deletes an item
126
     *
127
     * @param $id
128
     *
129
     * @return int
130
     * @throws ConstraintException
131
     * @throws QueryException
132
     */
133
    public function delete($id)
134
    {
135
        $queryData = new QueryData();
136
        $queryData->setQuery('DELETE FROM Notification WHERE id = ? AND sticky = 0 LIMIT 1');
137
        $queryData->addParam($id);
138
        $queryData->setOnErrorMessage(__u('Error al eliminar la notificación'));
139
140
        return $this->db->doQuery($queryData)->getAffectedNumRows();
141
    }
142
143
    /**
144
     * Deletes an item
145
     *
146
     * @param $id
147
     *
148
     * @return int
149
     * @throws ConstraintException
150
     * @throws QueryException
151
     */
152
    public function deleteAdmin($id)
153
    {
154
        $queryData = new QueryData();
155
        $queryData->setQuery('DELETE FROM Notification WHERE id = ? LIMIT 1');
156
        $queryData->addParam($id);
157
        $queryData->setOnErrorMessage(__u('Error al eliminar la notificación'));
158
159
        return $this->db->doQuery($queryData)->getAffectedNumRows();
160
    }
161
162
    /**
163
     * Deletes an item
164
     *
165
     * @param array $ids
166
     *
167
     * @return int
168
     * @throws ConstraintException
169
     * @throws QueryException
170
     */
171
    public function deleteAdminBatch(array $ids)
172
    {
173
        if (empty($ids)) {
174
            return 0;
175
        }
176
177
        $queryData = new QueryData();
178
        $queryData->setQuery('DELETE FROM Notification WHERE id IN (' . $this->getParamsFromArray($ids) . ')');
179
        $queryData->setParams($ids);
180
        $queryData->setOnErrorMessage(__u('Error al eliminar las notificaciones'));
181
182
        return $this->db->doQuery($queryData)->getAffectedNumRows();
183
    }
184
185
    /**
186
     * Returns the item for given id
187
     *
188
     * @param int $id
189
     *
190
     * @return QueryResult
191
     * @throws ConstraintException
192
     * @throws QueryException
193
     */
194
    public function getById($id)
195
    {
196
        $query = /** @lang SQL */
197
            'SELECT id, 
198
            type,
199
            component,
200
            description,
201
            `date`,
202
            userId,
203
            checked,
204
            sticky,
205
            onlyAdmin 
206
            FROM Notification 
207
            WHERE id = ? LIMIT 1';
208
209
        $queryData = new QueryData();
210
        $queryData->setMapClassName(NotificationData::class);
211
        $queryData->setQuery($query);
212
        $queryData->addParam($id);
213
        $queryData->setOnErrorMessage(__u('Error al obtener la notificación'));
214
215
        return $this->db->doSelect($queryData);
216
    }
217
218
    /**
219
     * Returns all the items
220
     *
221
     * @return QueryResult
222
     * @throws ConstraintException
223
     * @throws QueryException
224
     */
225
    public function getAll()
226
    {
227
        $query = /** @lang SQL */
228
            'SELECT id,
229
            type,
230
            component,
231
            description,
232
            `date`,
233
            userId,
234
            checked,
235
            sticky,
236
            onlyAdmin 
237
            FROM Notification
238
            ORDER BY id';
239
240
        $queryData = new QueryData();
241
        $queryData->setMapClassName(NotificationData::class);
242
        $queryData->setQuery($query);
243
        $queryData->setOnErrorMessage(__u('Error al obtener las notificaciones'));
244
245
        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...
246
    }
247
248
    /**
249
     * Returns all the items for given ids
250
     *
251
     * @param array $ids
252
     *
253
     * @return QueryResult
254
     * @throws ConstraintException
255
     * @throws QueryException
256
     */
257
    public function getByIdBatch(array $ids)
258
    {
259
        if (empty($ids)) {
260
            return new QueryResult();
0 ignored issues
show
Bug Best Practice introduced by
The expression return new SP\Storage\Database\QueryResult() returns the type SP\Storage\Database\QueryResult which is incompatible with the return type mandated by SP\Repositories\Reposito...terface::getByIdBatch() 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...
261
        }
262
263
        $query = /** @lang SQL */
264
            'SELECT id, 
265
            type,
266
            component,
267
            description,
268
            `date`,
269
            userId,
270
            checked,
271
            sticky,
272
            onlyAdmin 
273
            FROM Notification 
274
            WHERE id IN (' . $this->getParamsFromArray($ids) . ')
275
            ORDER BY id';
276
277
        $queryData = new QueryData();
278
        $queryData->setMapClassName(NotificationData::class);
279
        $queryData->setQuery($query);
280
        $queryData->setParams($ids);
281
282
        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\Reposito...terface::getByIdBatch() 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...
283
    }
284
285
    /**
286
     * Deletes all the items for given ids
287
     *
288
     * @param array $ids
289
     *
290
     * @return int
291
     * @throws ConstraintException
292
     * @throws QueryException
293
     */
294
    public function deleteByIdBatch(array $ids)
295
    {
296
        if (empty($ids)) {
297
            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...
298
        }
299
300
        $queryData = new QueryData();
301
        $queryData->setQuery('DELETE FROM Notification WHERE id IN (' . $this->getParamsFromArray($ids) . ') AND sticky = 0');
302
        $queryData->setParams($ids);
303
        $queryData->setOnErrorMessage(__u('Error al eliminar las notificaciones'));
304
305
        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...
306
    }
307
308
    /**
309
     * Checks whether the item is in use or not
310
     *
311
     * @param $id int
312
     */
313
    public function checkInUse($id)
314
    {
315
        throw new \RuntimeException('Not implemented');
316
    }
317
318
    /**
319
     * Checks whether the item is duplicated on updating
320
     *
321
     * @param mixed $itemData
322
     */
323
    public function checkDuplicatedOnUpdate($itemData)
324
    {
325
        throw new \RuntimeException('Not implemented');
326
    }
327
328
    /**
329
     * Checks whether the item is duplicated on adding
330
     *
331
     * @param mixed $itemData
332
     */
333
    public function checkDuplicatedOnAdd($itemData)
334
    {
335
        throw new \RuntimeException('Not implemented');
336
    }
337
338
    /**
339
     * Searches for items by a given filter
340
     *
341
     * @param ItemSearchData $itemSearchData
342
     *
343
     * @return QueryResult
344
     * @throws ConstraintException
345
     * @throws QueryException
346
     */
347
    public function search(ItemSearchData $itemSearchData)
348
    {
349
        $queryData = new QueryData();
350
        $queryData->setMapClassName(NotificationData::class);
351
        $queryData->setSelect('id, type, component, description, `date`, checked, userId, sticky, onlyAdmin');
352
        $queryData->setFrom('Notification');
353
        $queryData->setOrder('`date` DESC');
354
355
        if ($itemSearchData->getSeachString() !== '') {
356
            $queryData->setWhere('type LIKE ? OR component LIKE ? OR description LIKE ?');
357
358
            $search = '%' . $itemSearchData->getSeachString() . '%';
359
            $queryData->addParam($search);
360
            $queryData->addParam($search);
361
            $queryData->addParam($search);
362
        }
363
364
        $queryData->setLimit(
365
            '?,?',
366
            [$itemSearchData->getLimitStart(), $itemSearchData->getLimitCount()]
367
        );
368
369
        return $this->db->doSelect($queryData, true);
370
    }
371
372
    /**
373
     * Searches for items by a given filter
374
     *
375
     * @param ItemSearchData $itemSearchData
376
     * @param int            $userId
377
     *
378
     * @return QueryResult
379
     * @throws ConstraintException
380
     * @throws QueryException
381
     */
382
    public function searchForUserId(ItemSearchData $itemSearchData, $userId)
383
    {
384
        $queryData = new QueryData();
385
        $queryData->setMapClassName(NotificationData::class);
386
        $queryData->setSelect('id, type, component, description, `date`, checked, userId, sticky, onlyAdmin');
387
        $queryData->setFrom('Notification');
388
        $queryData->setOrder('`date` DESC');
389
390
        $queryCondition = new QueryCondition();
391
        $queryCondition->addFilter('userId = ?', [$userId]);
392
        $queryCondition->addFilter('(userId IS NULL AND onlyAdmin = 0)');
393
        $queryCondition->addFilter('sticky = 1');
394
395
        if ($itemSearchData->getSeachString() !== '') {
396
            $queryData->setWhere(
397
                '(type LIKE ? OR component LIKE ? OR description LIKE ?) AND '
398
                . $queryCondition->getFilters(QueryCondition::CONDITION_OR)
399
            );
400
401
            $search = '%' . $itemSearchData->getSeachString() . '%';
402
            $queryData->setParams(array_merge([$search, $search, $search], $queryCondition->getParams()));
403
        } else {
404
            $queryData->setWhere($queryCondition->getFilters(QueryCondition::CONDITION_OR));
405
            $queryData->setParams($queryCondition->getParams());
406
        }
407
408
        $queryData->setLimit(
409
            '?,?',
410
            [$itemSearchData->getLimitStart(), $itemSearchData->getLimitCount()]
411
        );
412
413
        return $this->db->doSelect($queryData, true);
414
    }
415
416
    /**
417
     * Searches for items by a given filter
418
     *
419
     * @param ItemSearchData $itemSearchData
420
     * @param int            $userId
421
     *
422
     * @return QueryResult
423
     * @throws ConstraintException
424
     * @throws QueryException
425
     */
426
    public function searchForAdmin(ItemSearchData $itemSearchData, $userId)
427
    {
428
        $queryData = new QueryData();
429
        $queryData->setMapClassName(NotificationData::class);
430
        $queryData->setSelect('id, type, component, description, `date`, checked, userId, sticky, onlyAdmin');
431
        $queryData->setFrom('Notification');
432
        $queryData->setOrder('`date` DESC');
433
434
        $queryCondition = new QueryCondition();
435
        $queryCondition->addFilter('userId = ?', [$userId]);
436
        $queryCondition->addFilter('onlyAdmin = 1');
437
        $queryCondition->addFilter('sticky = 1');
438
439
        if ($itemSearchData->getSeachString() !== '') {
440
            $queryData->setWhere(
441
                '(type LIKE ? OR component LIKE ? OR description LIKE ?) AND '
442
                . $queryCondition->getFilters(QueryCondition::CONDITION_OR)
443
            );
444
445
            $search = '%' . $itemSearchData->getSeachString() . '%';
446
447
            $queryData->setParams(array_merge([$search, $search, $search], $queryCondition->getParams()));
448
        } else {
449
            $queryData->setWhere($queryCondition->getFilters(QueryCondition::CONDITION_OR));
450
            $queryData->setParams($queryCondition->getParams());
451
        }
452
453
        $queryData->setLimit(
454
            '?,?',
455
            [$itemSearchData->getLimitStart(), $itemSearchData->getLimitCount()]
456
        );
457
458
        return $this->db->doSelect($queryData, true);
459
    }
460
461
    /**
462
     * Marcar una notificación como leída
463
     *
464
     * @param $id
465
     *
466
     * @return int
467
     * @throws ConstraintException
468
     * @throws QueryException
469
     */
470
    public function setCheckedById($id)
471
    {
472
        $query = /** @lang SQL */
473
            'UPDATE Notification SET checked = 1 WHERE id = ? LIMIT 1';
474
475
        $queryData = new QueryData();
476
        $queryData->setQuery($query);
477
        $queryData->addParam($id);
478
        $queryData->setOnErrorMessage(__u('Error al modificar la notificación'));
479
480
        return $this->db->doQuery($queryData)->getAffectedNumRows();
481
    }
482
483
    /**
484
     * Devolver las notificaciones de un usuario para una fecha y componente determinados
485
     *
486
     * @param $component
487
     * @param $userId
488
     *
489
     * @return QueryResult
490
     * @throws ConstraintException
491
     * @throws QueryException
492
     */
493
    public function getForUserIdByDate($component, $userId)
494
    {
495
        $query = /** @lang SQL */
496
            'SELECT id,
497
            type,
498
            component,
499
            description,
500
            `date`,
501
            userId,
502
            checked,
503
            sticky,
504
            onlyAdmin 
505
            FROM Notification 
506
            WHERE component = ?
507
            AND (UNIX_TIMESTAMP() - `date`) <= 86400
508
            AND userId = ?
509
            ORDER BY id';
510
511
        $queryData = new QueryData();
512
        $queryData->setMapClassName(NotificationData::class);
513
        $queryData->setQuery($query);
514
        $queryData->setParams([$component, $userId]);
515
        $queryData->setOnErrorMessage(__u('Error al obtener las notificaciones'));
516
517
        return $this->db->doSelect($queryData);
518
    }
519
520
    /**
521
     * @param $id
522
     *
523
     * @return QueryResult
524
     * @throws ConstraintException
525
     * @throws QueryException
526
     */
527
    public function getAllForUserId($id)
528
    {
529
        $query = /** @lang SQL */
530
            'SELECT id,
531
            type,
532
            component,
533
            description,
534
            `date`,
535
            userId,
536
            checked,
537
            sticky,
538
            onlyAdmin 
539
            FROM Notification 
540
            WHERE (userId = ? OR (userId IS NULL AND sticky = 1))
541
            AND onlyAdmin = 0 
542
            ORDER BY `date` DESC ';
543
544
        $queryData = new QueryData();
545
        $queryData->setMapClassName(NotificationData::class);
546
        $queryData->setQuery($query);
547
        $queryData->addParam($id);
548
        $queryData->setOnErrorMessage(__u('Error al obtener las notificaciones'));
549
550
        return $this->db->doSelect($queryData);
551
    }
552
553
    /**
554
     * @param $id
555
     *
556
     * @return QueryResult
557
     * @throws ConstraintException
558
     * @throws QueryException
559
     */
560
    public function getAllActiveForUserId($id)
561
    {
562
        $query = /** @lang SQL */
563
            'SELECT id,
564
            type,
565
            component,
566
            description,
567
            `date`,
568
            userId,
569
            checked,
570
            sticky,
571
            onlyAdmin 
572
            FROM Notification 
573
            WHERE (userId = ? OR sticky = 1) 
574
            AND onlyAdmin = 0 
575
            AND checked = 0
576
            ORDER BY `date` DESC ';
577
578
        $queryData = new QueryData();
579
        $queryData->setMapClassName(NotificationData::class);
580
        $queryData->setQuery($query);
581
        $queryData->addParam($id);
582
        $queryData->setOnErrorMessage(__u('Error al obtener las notificaciones'));
583
584
        return $this->db->doSelect($queryData);
585
    }
586
587
    /**
588
     * @param $id
589
     *
590
     * @return QueryResult
591
     * @throws ConstraintException
592
     * @throws QueryException
593
     */
594
    public function getAllActiveForAdmin($id)
595
    {
596
        $query = /** @lang SQL */
597
            'SELECT id,
598
            type,
599
            component,
600
            description,
601
            `date`,
602
            userId,
603
            checked,
604
            sticky,
605
            onlyAdmin 
606
            FROM Notification 
607
            WHERE (userId = ? OR sticky = 1 OR userId IS NULL) 
608
            AND checked = 0
609
            ORDER BY `date` DESC ';
610
611
        $queryData = new QueryData();
612
        $queryData->setMapClassName(NotificationData::class);
613
        $queryData->setQuery($query);
614
        $queryData->addParam($id);
615
        $queryData->setOnErrorMessage(__u('Error al obtener las notificaciones'));
616
617
        return $this->db->doSelect($queryData);
618
    }
619
}