Completed
Push — master ( 9abbc7...a687e5 )
by Fabrizio
03:03
created

NotificationRepository::getStack()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 24
Code Lines 16

Duplication

Lines 24
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 24
loc 24
rs 8.5125
cc 5
eloc 16
nc 4
nop 5
1
<?php
2
3
namespace Fenos\Notifynder\Notifications;
4
5
use Closure;
6
use Fenos\Notifynder\Contracts\NotificationDB;
7
use Fenos\Notifynder\Models\Notification;
8
use Illuminate\Database\DatabaseManager;
9
use Illuminate\Database\Connection;
10
use Illuminate\Database\Eloquent\Builder;
11
use Illuminate\Database\Query\Builder as BuilderDB;
12
13
/**
14
 * Class NotificationRepository.
15
 */
16
class NotificationRepository implements NotificationDB
17
{
18
    /**
19
     * @var Notification | Builder | BuilderDB
20
     */
21
    protected $notification;
22
23
    /**
24
     * @var DatabaseManager | Connection
25
     */
26
    protected $db;
27
28
    /**
29
     * @param Notification                         $notification
30
     * @param \Illuminate\Database\DatabaseManager $db
31
     */
32
    public function __construct(
33
        Notification $notification,
34
        DatabaseManager $db
35
    ) {
36
        $this->notification = $notification;
37
        $this->db = $db;
38
    }
39
40
    /**
41
     * Find notification by id.
42
     *
43
     * @param $notificationId
44
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|static
45
     */
46
    public function find($notificationId)
47
    {
48
        return $this->notification->find($notificationId);
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<Fenos\Notifynder\Models\Notification>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
49
    }
50
51
    /**
52
     * Save a single notification sent.
53
     *
54
     * @param  array $info
55
     * @return Notification
56
     */
57
    public function storeSingle(array $info)
58
    {
59
        return $this->notification->create($info);
60
    }
61
62
    /**
63
     * Save multiple notifications sent
64
     * at once.
65
     *
66
     * @param  array $notifications
67
     * @return mixed
68
     */
69
    public function storeMultiple(array $notifications)
70
    {
71
        $this->db->beginTransaction();
72
        $stackId = $this->db->table(
73
            $this->notification->getTable()
74
        )->max('stack_id') + 1;
75
        foreach ($notifications as $key => $notification) {
76
            $notifications[$key]['stack_id'] = $stackId;
77
        }
78
        $insert = $this->db->table(
79
            $this->notification->getTable()
80
        )->insert($notifications);
81
        $this->db->commit();
82
83
        return $insert;
84
    }
85
86
    /**
87
     * Make Read One Notification.
88
     *
89
     * @param  Notification $notification
90
     * @return bool|Notification
91
     */
92
    public function readOne(Notification $notification)
93
    {
94
        $notification->read = 1;
95
96
        if ($notification->save()) {
97
            return $notification;
98
        }
99
100
        return false;
101
    }
102
103
    /**
104
     * Read notifications in base the number
105
     * Given.
106
     *
107
     * @param $toId
108
     * @param $entity
109
     * @param $numbers
110
     * @param $order
111
     * @return int
112
     */
113
    public function readLimit($toId, $entity, $numbers, $order)
114
    {
115
        $notifications = $this->notification->withNotRead()
0 ignored issues
show
Bug introduced by
The method withNotRead() does not exist on Fenos\Notifynder\Models\Notification. Did you maybe mean scopeWithNotRead()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
116
            ->wherePolymorphic($toId, $entity)
117
            ->limit($numbers)
118
            ->orderBy('id', $order)
119
            ->lists('id');
120
121
        return $this->notification->whereIn('id', $notifications)
0 ignored issues
show
Documentation Bug introduced by
The method whereIn does not exist on object<Fenos\Notifynder\Models\Notification>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
122
            ->update(['read' => 1]);
123
    }
124
125
    /**
126
     * Make read all notification not read.
127
     *
128
     * @param $toId
129
     * @param $entity
130
     * @return int
131
     */
132
    public function readAll($toId, $entity)
133
    {
134
        return $this->notification->withNotRead()
0 ignored issues
show
Bug introduced by
The method withNotRead() does not exist on Fenos\Notifynder\Models\Notification. Did you maybe mean scopeWithNotRead()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
135
            ->wherePolymorphic($toId, $entity)
136
            ->update(['read' => 1]);
137
    }
138
139
    /**
140
     * Delete a notification giving the id
141
     * of it.
142
     *
143
     * @param $notificationId
144
     * @return bool
145
     */
146
    public function delete($notificationId)
147
    {
148
        return $this->notification->where('id', $notificationId)->delete();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<Fenos\Notifynder\Models\Notification>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
149
    }
150
151
    /**
152
     * Delete All notifications about the
153
     * current user.
154
     *
155
     * @param $toId int
156
     * @param $entity
157
     * @return bool
158
     */
159
    public function deleteAll($toId, $entity)
160
    {
161
        $query = $this->db->table(
162
            $this->notification->getTable()
163
        );
164
165
        return $this->notification->scopeWherePolymorphic($query, $toId, $entity)
166
            ->delete();
167
    }
168
169
    /**
170
     * Delete All notifications from a
171
     * defined category.
172
     *
173
     * @param $categoryName int
174
     * @param $expired       Bool
175
     * @return bool
176
     */
177
    public function deleteByCategory($categoryName, $expired = false)
178
    {
179
        $query = $this->notification->whereHas(
0 ignored issues
show
Documentation Bug introduced by
The method whereHas does not exist on object<Fenos\Notifynder\Models\Notification>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
180
            'body',
181
            function ($query) use ($categoryName) {
182
                $query->where('name', $categoryName);
183
            }
184
        );
185
186
        if ($expired == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
187
            return $query->onlyExpired()->delete();
188
        }
189
190
        return $query->delete();
191
    }
192
193
    /**
194
     * Delete numbers of notifications equals
195
     * to the number passing as 2 parameter of
196
     * the current user.
197
     *
198
     * @param $userId    int
199
     * @param $entity
200
     * @param $number     int
201
     * @param $order      string
202
     * @return int
203
     * @throws \Exception
204
     */
205
    public function deleteLimit($userId, $entity, $number, $order)
206
    {
207
        $notificationsIds = $this->notification
0 ignored issues
show
Bug introduced by
The method wherePolymorphic() does not exist on Fenos\Notifynder\Models\Notification. Did you maybe mean scopeWherePolymorphic()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
208
            ->wherePolymorphic($userId, $entity)
209
            ->orderBy('id', $order)
210
            ->select('id')
211
            ->limit($number)
212
            ->lists('id');
213
214
        if (count($notificationsIds) == 0) {
215
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type declared by the interface Fenos\Notifynder\Contrac...ficationDB::deleteLimit of type integer.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
216
        }
217
218
        return $this->notification->whereIn('id', $notificationsIds)
0 ignored issues
show
Documentation Bug introduced by
The method whereIn does not exist on object<Fenos\Notifynder\Models\Notification>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
219
            ->delete();
220
    }
221
222
    /**
223
     * Retrieve notifications not Read
224
     * You can also limit the number of
225
     * Notification if you don't it will get all.
226
     *
227
     * @param              $toId
228
     * @param              $entity
229
     * @param  int|null    $limit
230
     * @param  int|null    $paginate
231
     * @param  string      $orderDate
232
     * @param Closure|null $filterScope
233
     * @return mixed
234
     */
235 View Code Duplication
    public function getNotRead(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
236
        $toId,
237
        $entity,
238
        $limit = null,
239
        $paginate = null,
240
        $orderDate = 'desc',
241
        Closure $filterScope = null
242
    ) {
243
        $query = $this->notification->with('body', 'from')
244
            ->wherePolymorphic($toId, $entity)
245
            ->withNotRead()
246
            ->orderBy('read', 'ASC')
247
            ->orderBy('created_at', $orderDate);
248
249
        if ($limit && ! $paginate) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $limit of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
Bug Best Practice introduced by
The expression $paginate of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
250
            $query->limit($limit);
251
        }
252
253
        $query = $this->applyFilter($filterScope, $query);
254
255
        if (is_int(intval($paginate)) && $paginate) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $paginate of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
256
            return $query->paginate($limit);
257
        }
258
259
        return $query->get();
260
    }
261
262
    /**
263
     * Retrieve all notifications, not read
264
     * in first.
265
     * You can also limit the number of
266
     * Notifications if you don't, it will get all.
267
     *
268
     * @param           $toId
269
     * @param           $entity
270
     * @param  null     $limit
271
     * @param  int|null $paginate
272
     * @param  string   $orderDate
273
     * @param Closure   $filterScope
274
     * @return mixed
275
     */
276 View Code Duplication
    public function getAll(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
277
        $toId,
278
        $entity,
279
        $limit = null,
280
        $paginate = null,
281
        $orderDate = 'desc',
282
        Closure $filterScope = null
283
    ) {
284
        $query = $this->notification->with('body', 'from')
285
            ->wherePolymorphic($toId, $entity)
286
            ->orderBy('read', 'ASC')
287
            ->orderBy('created_at', $orderDate);
288
289
        if ($limit && ! $paginate) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $paginate of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
290
            $query->limit($limit);
291
        }
292
293
        $query = $this->applyFilter($filterScope, $query);
294
295
        if (is_int(intval($paginate)) && $paginate) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $paginate of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
296
            return $query->paginate($limit);
297
        }
298
299
        return $query->get();
300
    }
301
302
    /**
303
     * get number Notifications
304
     * not read.
305
     *
306
     * @param         $toId
307
     * @param         $entity
308
     * @param Closure $filterScope
309
     * @return mixed
310
     */
311 View Code Duplication
    public function countNotRead($toId, $entity, Closure $filterScope = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
312
    {
313
        $query = $this->notification->wherePolymorphic($toId, $entity)
0 ignored issues
show
Bug introduced by
The method wherePolymorphic() does not exist on Fenos\Notifynder\Models\Notification. Did you maybe mean scopeWherePolymorphic()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
314
            ->withNotRead()
315
            ->select($this->db->raw('Count(*) as notRead'));
316
317
        $query = $this->applyFilter($filterScope, $query);
318
319
        return $query->count();
320
    }
321
322
    /**
323
     * Get last notification of the current
324
     * entity.
325
     *
326
     * @param         $toId
327
     * @param         $entity
328
     * @param Closure $filterScope
329
     * @return mixed
330
     */
331 View Code Duplication
    public function getLastNotification($toId, $entity, Closure $filterScope = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
332
    {
333
        $query = $this->notification->wherePolymorphic($toId, $entity)
0 ignored issues
show
Bug introduced by
The method wherePolymorphic() does not exist on Fenos\Notifynder\Models\Notification. Did you maybe mean scopeWherePolymorphic()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
334
            ->orderBy('created_at', 'DESC');
335
336
        $query = $this->applyFilter($filterScope, $query);
337
338
        return $query->first();
339
    }
340
341
    /**
342
     * Get last notification of the current
343
     * entity of a specific category.
344
     *
345
     * @param         $category
346
     * @param         $toId
347
     * @param         $entity
348
     * @param Closure $filterScope
349
     * @return mixed
350
     */
351 View Code Duplication
    public function getLastNotificationByCategory($category, $toId, $entity, Closure $filterScope = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
352
    {
353
        $query = $this->notification
0 ignored issues
show
Bug introduced by
The method wherePolymorphic() does not exist on Fenos\Notifynder\Models\Notification. Did you maybe mean scopeWherePolymorphic()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
354
            ->wherePolymorphic($toId, $entity)
355
            ->byCategory($category)
356
            ->orderBy('created_at', 'desc');
357
358
        $query = $this->applyFilter($filterScope, $query);
359
360
        return $query->first();
361
    }
362
363
    /**
364
     * Apply scope filters.
365
     *
366
     * @param Closure $filterScope
367
     * @param         $query
368
     */
369
    protected function applyFilter(Closure $filterScope = null, $query)
370
    {
371
        if (! $filterScope) {
372
            return $query;
373
        }
374
375
        $filterScope($query);
376
377
        return $query;
378
    }
379
380
    /**
381
     * Retrive all notifications, in a stack.
382
     * You can also limit the number of
383
     * Notifications if you don't, it will get all.
384
     *
385
     * @param           $stackId
386
     * @param  null     $limit
387
     * @param  int|null $paginate
388
     * @param  string   $orderDate
389
     * @param Closure   $filterScope
390
     * @return mixed
391
     */
392 View Code Duplication
    public function getStack(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
393
        $stackId,
394
        $limit = null,
395
        $paginate = null,
396
        $orderDate = 'desc',
397
        Closure $filterScope = null
398
    ) {
399
        $query = $this->notification->with('body', 'from', 'to')
400
            ->byStack($stackId)
401
            ->orderBy('read', 'ASC')
402
            ->orderBy('created_at', $orderDate);
403
404
        if ($limit && ! $paginate) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $paginate of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
405
            $query->limit($limit);
406
        }
407
408
        $query = $this->applyFilter($filterScope, $query);
409
410
        if (is_int(intval($paginate)) && $paginate) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $paginate of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
411
            return $query->paginate($limit);
412
        }
413
414
        return $query->get();
415
    }
416
}
417