Completed
Push — master ( ab3f56...9b4153 )
by Fabrizio
07:38
created

NotificationRepository::getAll()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 21
Code Lines 15

Duplication

Lines 21
Ratio 100 %

Importance

Changes 5
Bugs 2 Features 2
Metric Value
c 5
b 2
f 2
dl 21
loc 21
rs 9.3142
cc 3
eloc 15
nc 2
nop 6
1
<?php namespace Fenos\Notifynder\Notifications;
2
3
use Closure;
4
use Fenos\Notifynder\Contracts\NotificationDB;
5
use Fenos\Notifynder\Models\Notification;
6
use Illuminate\Database\DatabaseManager;
7
use Illuminate\Database\Connection;
8
use Illuminate\Database\Eloquent\Builder;
9
use Illuminate\Database\Query\Builder as BuilderDB;
10
11
/**
12
 * Class NotificationRepository
13
 *
14
 * @package Fenos\Notifynder\Senders
15
 */
16
class NotificationRepository implements NotificationDB
17
{
18
19
    /**
20
     * @var Notification | Builder | BuilderDB
21
     */
22
    protected $notification;
23
24
    /**
25
     * @var $db DatabaseManager | Connection
26
     */
27
    protected $db;
28
29
    /**
30
     * @param Notification                         $notification
31
     * @param \Illuminate\Database\DatabaseManager $db
32
     */
33
    public function __construct(
34
        Notification $notification,
35
        DatabaseManager $db
36
    ) {
37
        $this->notification = $notification;
38
        $this->db = $db;
39
    }
40
41
    /**
42
     * Find notification by id
43
     *
44
     * @param $notification_id
45
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|static
46
     */
47
    public function find($notification_id)
48
    {
49
        return $this->notification->find($notification_id);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->notification->find($notification_id); of type Illuminate\Database\Eloq...e\Eloquent\Builder|null adds the type Illuminate\Database\Eloquent\Builder to the return on line 49 which is incompatible with the return type declared by the interface Fenos\Notifynder\Contracts\NotificationDB::find of type Illuminate\Database\Eloq...ontracts\NotificationDB.
Loading history...
50
    }
51
52
    /**
53
     * Save a single notification sent
54
     *
55
     * @param  array $info
56
     * @return Notification
57
     */
58
    public function storeSingle(array $info)
59
    {
60
        return $this->notification->create($info);
61
    }
62
63
    /**
64
     * Save multiple notifications sent
65
     * at once
66
     *
67
     * @param  array $info
68
     * @return mixed
69
     */
70
    public function storeMultiple(array $info)
71
    {
72
        return $this->db->table(
73
            $this->notification->getTable()
74
        )->insert($info);
75
    }
76
77
    /**
78
     * Make Read One Notification
79
     *
80
     * @param  Notification $notification
81
     * @return bool|Notification
82
     */
83
    public function readOne(Notification $notification)
84
    {
85
        $notification->read = 1;
86
87
        if ($notification->save()) {
88
            return $notification;
89
        }
90
91
        return false;
92
    }
93
94
    /**
95
     * Read notifications in base the number
96
     * Given
97
     *
98
     * @param $to_id
99
     * @param $entity
100
     * @param $numbers
101
     * @param $order
102
     * @return int
103
     */
104
    public function readLimit($to_id, $entity, $numbers, $order)
105
    {
106
        $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...
107
            ->wherePolymorphic($to_id, $entity)
108
            ->limit($numbers)
109
            ->orderBy('id', $order)
110
            ->lists('id');
111
112
        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...
113
            ->update(['read' => 1]);
114
    }
115
116
    /**
117
     * Make read all notification not read
118
     *
119
     * @param $to_id
120
     * @param $entity
121
     * @return int
122
     */
123
    public function readAll($to_id, $entity)
124
    {
125
        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...
126
            ->wherePolymorphic($to_id, $entity)
127
            ->update(['read' => 1]);
128
    }
129
130
    /**
131
     * Delete a notification giving the id
132
     * of it
133
     *
134
     * @param $notification_id
135
     * @return Bool
136
     */
137
    public function delete($notification_id)
138
    {
139
        return $this->notification->where('id', $notification_id)->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...
140
    }
141
142
    /**
143
     * Delete All notifications about the
144
     * current user
145
     *
146
     * @param $to_id int
147
     * @param $entity
148
     * @return Bool
149
     */
150
    public function deleteAll($to_id, $entity)
151
    {
152
        $query = $this->db->table(
153
            $this->notification->getTable()
154
        );
155
156
        return $this->notification->scopeWherePolymorphic($query, $to_id, $entity)
157
            ->delete();
158
    }
159
160
    /**
161
     * Delete All notifications from a
162
     * defined category
163
     *
164
     * @param $category_name int
165
     * @param $expired       Bool
166
     * @return Bool
167
     */
168
    public function deleteByCategory($category_name, $expired = false)
169
    {
170
        $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...
171
            'body',
172
            function ($q) use ($category_name) {
173
                $q->where('name', $category_name);
174
            }
175
        );
176
177
        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...
178
            return $query->onlyExpired()->delete();
179
        }
180
181
        return $query->delete();
182
    }
183
184
    /**
185
     *
186
     * Delete numbers of notifications equals
187
     * to the number passing as 2 parameter of
188
     * the current user
189
     *
190
     * @param $user_id    int
191
     * @param $entity
192
     * @param $number     int
193
     * @param $order      string
194
     * @return int
195
     * @throws \Exception
196
     */
197
    public function deleteLimit($user_id, $entity, $number, $order)
198
    {
199
        $notifications_ids = $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...
200
            ->wherePolymorphic($user_id, $entity)
201
            ->orderBy('id', $order)
202
            ->select('id')
203
            ->limit($number)
204
            ->lists('id');
205
206
        if (count($notifications_ids) == 0) {
207
            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...
208
        }
209
210
        return $this->notification->whereIn('id', $notifications_ids)
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...
211
            ->delete();
212
    }
213
214
    /**
215
     * Retrive notifications not Read
216
     * You can also limit the number of
217
     * Notification if you don't it will get all
218
     *
219
     * @param              $to_id
220
     * @param              $entity
221
     * @param  int|null    $limit
222
     * @param  int|null    $paginate
223
     * @param  string      $orderDate
224
     * @param Closure|null $filterScope
225
     * @return mixed
226
     */
227 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...
228
        $to_id,
229
        $entity,
230
        $limit = null,
231
        $paginate = null,
232
        $orderDate = 'desc',
233
        Closure $filterScope = null
234
    ) {
235
        $query = $this->notification->with('body', 'from')
236
            ->wherePolymorphic($to_id, $entity)
237
            ->withNotRead()
238
            ->orderBy('read', 'ASC')
239
            ->orderBy('created_at', $orderDate);
240
241
        $query = $this->applyFilter($filterScope, $query);
242
243
        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...
244
            return $query->paginate($limit);
245
        }
246
247
        return $query->get();
248
    }
249
250
    /**
251
     * Retrive all notifications, not read
252
     * in first.
253
     * You can also limit the number of
254
     * Notifications if you don't, it will get all
255
     *
256
     * @param           $to_id
257
     * @param           $entity
258
     * @param  null     $limit
259
     * @param  int|null $paginate
260
     * @param  string   $orderDate
261
     * @param Closure   $filterScope
262
     * @return mixed
263
     */
264 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...
265
        $to_id,
266
        $entity,
267
        $limit = null,
268
        $paginate = null,
269
        $orderDate = 'desc',
270
        Closure $filterScope = null
271
    ) {
272
        $query = $this->notification->with('body', 'from')
273
            ->wherePolymorphic($to_id, $entity)
274
            ->orderBy('read', 'ASC')
275
            ->orderBy('created_at', $orderDate);
276
277
        $query = $this->applyFilter($filterScope, $query);
278
279
        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...
280
            return $query->paginate($limit);
281
        }
282
283
        return $query->get();
284
    }
285
286
    /**
287
     * get number Notifications
288
     * not read
289
     *
290
     * @param         $to_id
291
     * @param         $entity
292
     * @param Closure $filterScope
293
     * @return mixed
294
     */
295 View Code Duplication
    public function countNotRead($to_id, $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...
296
    {
297
        $query = $this->notification->wherePolymorphic($to_id, $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...
298
            ->withNotRead()
299
            ->select($this->db->raw('Count(*) as notRead'));
300
301
        $query = $this->applyFilter($filterScope, $query);
302
303
        return $query->count();
304
    }
305
306
    /**
307
     * Get last notification of the current
308
     * entity
309
     *
310
     * @param         $to_id
311
     * @param         $entity
312
     * @param Closure $filterScope
313
     * @return mixed
314
     */
315 View Code Duplication
    public function getLastNotification($to_id, $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...
316
    {
317
        $query = $this->notification->wherePolymorphic($to_id, $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...
318
            ->orderBy('created_at', 'DESC');
319
320
        $query = $this->applyFilter($filterScope, $query);
321
322
        return $query->first();
323
    }
324
325
    /**
326
     * Get last notification of the current
327
     * entity of a specific category
328
     *
329
     * @param         $category
330
     * @param         $to_id
331
     * @param         $entity
332
     * @param Closure $filterScope
333
     * @return mixed
334
     */
335 View Code Duplication
    public function getLastNotificationByCategory($category, $to_id, $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...
336
    {
337
        $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...
338
            ->wherePolymorphic($to_id, $entity)
339
            ->byCategory($category)
340
            ->orderBy('created_at', 'desc');
341
342
        $query = $this->applyFilter($filterScope, $query);
343
344
        return $query->first();
345
    }
346
347
    /**
348
     * Apply scope filters
349
     *
350
     * @param Closure $filterScope
351
     * @param         $query
352
     */
353
    protected function applyFilter(Closure $filterScope = null, $query)
354
    {
355
        if ( ! $filterScope) {
356
            return $query;
357
        }
358
359
        $filterScope($query);
360
361
        return $query;
362
    }
363
}
364