NotificationService::usersAsOptions()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
namespace Transmissor\Services;
4
5
use Crypto;
6
use Illuminate\Support\Facades\Schema;
7
use Transmissor\Models\Notification;
8
use Transmissor\Notifications\GeneralNotification;
9
use Transmissor\Services\UserService;
10
11
class NotificationService
12
{
13
    public function __construct(
14
        Notification $model,
15
        UserService $userService
16
    ) {
17
        $this->model = $model;
0 ignored issues
show
Bug introduced by
The property model does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
18
        $this->userService = $userService;
0 ignored issues
show
Bug introduced by
The property userService does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
19
    }
20
21
    /**
22
     * All notifications
23
     *
24
     * @return Collection
25
     */
26
    public function all()
27
    {
28
        return $this->model->orderBy('created_at', 'desc')->get();
29
    }
30
31
    /**
32
     * Paginated notifications
33
     *
34
     * @return PaginatedCollection
35
     */
36
    public function paginated()
37
    {
38
        return $this->model->orderBy('created_at', 'desc')->paginate(env('PAGINATE', 25));
39
    }
40
41
    /**
42
     * User based paginated notifications
43
     *
44
     * @param  integer $id
45
     * @return PaginatedCollection
46
     */
47
    public function userBasedPaginated($id)
48
    {
49
        return $this->model->where('notificable_type', User::class)->where('notificable_id', $id)->orderBy('created_at', 'desc')->paginate(env('PAGINATE', 25));
50
    }
51
52
    /**
53
     * User based notifications
54
     *
55
     * @param  integer $id
56
     * @return Collection
57
     */
58
    public function userBased($id)
59
    {
60
        return $this->model->where('notificable_type', User::class)->where('notificable_id', $id)->where('deleted_at', null)->orderBy('created_at', 'desc')->get();
61
    }
62
63
    /**
64
     * Search notifications
65
     *
66
     * @param  string  $input
67
     * @param  integer $id
68
     * @return Collection
69
     */
70
    public function search($input, $id)
71
    {
72
        $query = $this->model->orderBy('created_at', 'desc');
73
        $query->where('id', 'LIKE', '%'.$input.'%');
74
75
        $columns = Schema::getColumnListing('notifications');
76
77
        foreach ($columns as $attribute) {
78
            if (is_null($id)) {
79
                $query->orWhere($attribute, 'LIKE', '%'.$input.'%');
80
            } else {
81
                $query->orWhere($attribute, 'LIKE', '%'.$input.'%')->where('user_id', $id);
82
            }
83
        };
84
85
        return $query->paginate(env('PAGINATE', 25));
86
    }
87
88
    /**
89
     * Create a notificaton
90
     *
91
     * @param  integer $userId
92
     * @param  string  $flag
93
     * @param  string  $title
94
     * @param  string  $details
95
     * @return void
96
     */
97
    public function notify($userId, $flag, $title, $details)
98
    {
99
        $input = [
100
            'notificable_type' => User::class,
101
            'notificable_id' => $userId,
102
            'flag' => $flag,
103
            'title' => $title,
104
            'details' => $details,
105
        ];
106
107
        $this->create($input);
108
    }
109
110
    /**
111
     * Create a notification
112
     *
113
     * @param  array $input
114
     * @return boolean|exception
115
     */
116
    public function create($input)
117
    {
118
        try {
119
            if ($input['user_id'] == 0) {
120
                $users = $this->userService->all();
121
122
                foreach ($users as $user) {
123
                    $input['uuid'] = Crypto::uuid();
124
                    $input['user_id'] = $user->id;
125
                    $this->model->create($input);
126
                }
127
128
                $user->notify(
0 ignored issues
show
Bug introduced by
The variable $user seems to be defined by a foreach iteration on line 122. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
129
                    new GeneralNotification(
130
                        [
131
                        'title' => $input['title'],
132
                        'details' => $input['details'],
133
                        ]
134
                    )
135
                );
136
137
                return true;
138
            }
139
140
            $input['uuid'] = Crypto::uuid();
141
142
            $user = $this->userService->find($input['user_id']);
143
            $user->notify(
144
                new GeneralNotification(
145
                    [
146
                    'title' => $input['title'],
147
                    'details' => $input['details'],
148
                    ]
149
                )
150
            );
151
152
            return $this->model->create($input);
153
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class Transmissor\Services\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
154
            throw new Exception("Could not send notifications please try agian.", 1);
155
        }
156
    }
157
158
    /**
159
     * Get a user
160
     *
161
     * @param  integer $id
162
     * @return User
163
     */
164
    public function getUser($id)
165
    {
166
        return $this->userService->find($id);
167
    }
168
169
    /**
170
     * Find a notification
171
     *
172
     * @param  integer $id
173
     * @return Notification
174
     */
175
    public function find($id)
176
    {
177
        return $this->model->find($id);
178
    }
179
180
    /**
181
     * Find a notification by UUID
182
     *
183
     * @param  string $uuid
184
     * @return Notification
185
     */
186
    public function findByUuid($uuid)
187
    {
188
        return $this->model->where('uuid', $uuid)->first();
189
    }
190
191
    /**
192
     * Update a notification
193
     *
194
     * @param  integer $id
195
     * @param  array   $input
196
     * @return Notification
197
     */
198
    public function update($id, $input)
199
    {
200
        $notification = $this->model->find($id);
201
        $notification->update($input);
202
203
        $user = $this->userService->find($notification->user_id);
204
        $user->notify(
205
            new GeneralNotification(
206
                [
207
                'title' => $input['title'],
208
                'details' => $input['details'],
209
                ]
210
            )
211
        );
212
213
        return $notification;
214
    }
215
216
    /**
217
     * Mark notification as read
218
     *
219
     * @param  integer $id
220
     * @return boolean
221
     */
222
    public function markAsRead($id)
223
    {
224
        $input['is_read'] = true;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$input was never initialized. Although not strictly required by PHP, it is generally a good practice to add $input = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
225
        return $this->model->find($id)->update($input);
226
    }
227
228
    /**
229
     * Destroy a Notification
230
     *
231
     * @param  integer $id
232
     * @return boolean
233
     */
234
    public function destroy($id)
235
    {
236
        return $this->model->find($id)->delete();
237
    }
238
239
    /**
240
     * Users as Select options array
241
     *
242
     * @return Array
243
     */
244
    public function usersAsOptions()
245
    {
246
        $users = ['All' => 0];
247
248
        foreach ($this->userService->all() as $user) {
249
            $users[$user->name] = $user->id;
250
        }
251
252
        return $users;
253
    }
254
}
255