Completed
Push — develop ( 1c3d8e...dc7d05 )
by Mohamed
07:44
created

SendMessagesAbstract::setMailer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
/*
4
 * This file is part of the Tinyissue package.
5
 *
6
 * (c) Mohamed Alsharaf <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Tinyissue\Services;
13
14
use Illuminate\Mail\Message as MailMessage;
15
use Illuminate\Support\Collection;
16
use Illuminate\Contracts\Mail\Mailer;
17
use Tinyissue\Http\Requests\FormRequest\Note;
18
use Tinyissue\Model\Message;
19
use Tinyissue\Model\Project;
20
use Tinyissue\Model\Project\Issue;
21
use Tinyissue\Model\Role;
22
use Tinyissue\Model\User;
23
24
/**
25
 * SendMessagesAbstract is an abstract class with for objects that requires sending messages.
26
 *
27
 * @author Mohamed Alsharaf <[email protected]>
28
 */
29
abstract class SendMessagesAbstract
30
{
31
    /**
32
     * Instance of issue that this message belong to.
33
     *
34
     * @var Issue
35
     */
36
    protected $issue;
37
38
    /**
39
     * Instance of project that this message belong to.
40
     *
41
     * @var Issue
42
     */
43
    protected $project;
44
45
    /**
46
     * The latest message queued.
47
     *
48
     * @var Message\Queue
49
     */
50
    protected $latestMessage;
51
52
    /**
53
     * Collection of all of the queued messages.
54
     *
55
     * @var Collection
56
     */
57
    protected $allMessages;
58
59
    /**
60
     * Instance of a queued message that is for adding a record (ie. adding issue).
61
     *
62
     * @var Message\Queue
63
     */
64
    protected $addMessage;
65
    /**
66
     * Collection of users that must not receive messages.
67
     *
68
     * @var Collection
69
     */
70
    protected $excludeUsers;
71
    /**
72
     * Collection of all of the project users that should receive messages.
73
     *
74
     * @var Collection
75
     */
76
    protected $projectUsers;
77
    /**
78
     * Collection of full subscribers that will always receive messages.
79
     *
80
     * @var Collection
81
     */
82
    protected $fullSubscribers;
83
    /**
84
     * Name of message template.
85
     *
86
     * @var string
87
     */
88
    protected $template;
89
90
    /**
91
     * @var Mailer
92
     */
93
    protected $mailer;
94
95
    /**
96
     * Collection of all messages.
97
     *
98
     * @var Collection
99
     */
100
    protected $messages;
101
102
    /**
103
     * Set instance of Mailer.
104
     *
105
     * @param Mailer $mailer
106
     *
107
     * @return $this
108
     */
109 4
    public function setMailer(Mailer $mailer)
110
    {
111 4
        $this->mailer = $mailer;
112
113 4
        return $this;
114
    }
115
116
    /**
117
     * The main method to process the massages queue and send them.
118
     *
119
     * @param Message\Queue $latestMessage
120
     * @param Collection    $changes
121
     *
122
     * @return void
123
     */
124 4
    public function process(Message\Queue $latestMessage, Collection $changes)
125
    {
126 4
        $this->setup($latestMessage, $changes);
127
128
        // Is model deleted?
129 4
        if (!$this->getModel()) {
130 2
            return $this->sendMessageToAll($this->latestMessage);
131
        }
132
133 4
        if (!$this->validateData()) {
134
            return;
135
        }
136
137 4
        $this->processDirectMessages();
138
139
        // Skip if no users found
140 4
        if ($this->getProjectUsers()->isEmpty()) {
141
            return;
142
        }
143
144 4
        $this->populateData();
145
146
        // Send the latest message if it is about status (ie. closed issue)
147 4
        if ($this->isStatusMessage()) {
148 2
            return $this->sendMessageToAll($this->latestMessage);
149
        }
150
151
        // Get message data for all of the messages combined & for add message queue if exists
152 4
        $addMessageData = [];
153 4
        if ($this->addMessage) {
154 4
            $addMessageData = $this->getMessageData($this->addMessage);
155
        }
156 4
        $everythingMessageData = $this->getCombineMessageData($this->allMessages);
157
158
        // Send messages to project users
159 4
        $this->sendMessages($this->getProjectUsers(), [
160 4
            'addMessage' => $addMessageData,
161 4
            'everything' => $everythingMessageData,
162
        ]);
163 4
    }
164
165
    /**
166
     * Setup properties needed for the process.
167
     *
168
     * @param Message\Queue $latestMessage
169
     * @param Collection    $allMessages
170
     *
171
     * @return void
172
     */
173 4
    protected function setup(Message\Queue $latestMessage, Collection $allMessages)
174
    {
175
        // Set queue messages
176 4
        $this->latestMessage = $latestMessage;
177 4
        $this->allMessages   = $allMessages;
178
179
        // Exclude the user who made the change from receiving messages
180 4
        $this->addToExcludeUsers($this->latestMessage->changeBy);
0 ignored issues
show
Documentation introduced by
$this->latestMessage->changeBy is of type object<Tinyissue\Model\Project\User>, but the function expects a object<Tinyissue\Model\User>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
181
182
        // Extract add model message if exists
183 4
        if ($this->getModel()) {
184 4
            $addMessageIdentifier = Message\Queue::getAddEventNameFromModel($this->getModel());
0 ignored issues
show
Bug introduced by
It seems like $this->getModel() targeting Tinyissue\Services\SendM...gesAbstract::getModel() can also be of type object<Tinyissue\Http\Requests\FormRequest\Note>; however, Tinyissue\Model\Message\...AddEventNameFromModel() does only seem to accept object<Illuminate\Database\Eloquent\Model>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
185 4
            $this->addMessage = $this->allMessages->where('event', $addMessageIdentifier)->first();
186
        }
187
188
        // Make sure to load issue
189 4
        $this->getIssue();
190 4
    }
191
192
    /**
193
     * Whether or not we have all the needed properties.
194
     *
195
     * @return bool
196
     */
197
    abstract protected function validateData();
198
199
    /**
200
     * Process any messages queue that is to send messages to specific users.
201
     * For example, assign issue to user to message the user about the issue.
202
     *
203
     * @return void
204
     */
205 2
    protected function processDirectMessages()
206
    {
207 2
    }
208
209
    /**
210
     * Populate any data or properties.
211
     *
212
     * @return void
213
     */
214 1
    protected function populateData()
215
    {
216 1
    }
217
218
    /**
219
     * Whether or not the latest message is about status change such as closed issue.
220
     *
221
     * @return bool
222
     */
223
    abstract public function isStatusMessage();
224
225
    /**
226
     * Returns the message subject.
227
     *
228
     * @return string
229
     */
230 3
    protected function getSubject()
231
    {
232 3
        return '#' . $this->issue->id . ' / ' . $this->issue->title;
233
    }
234
235
    /**
236
     * Returns an array of data needed for the message.
237
     *
238
     * @param Message\Queue $queue
239
     * @param array         $extraData
240
     *
241
     * @return array
242
     */
243 4
    protected function getMessageData(Message\Queue $queue, array $extraData = [])
244
    {
245
        // Generic info for all messages emails
246 4
        $messageData                         = [];
247 4
        $messageData['issue']                = $this->getIssue();
248 4
        $messageData['project']              = $this->getProject();
249 4
        $messageData['changes']              = [];
250 4
        $messageData['changes']['change_by'] = [
251 4
            'now' => $queue->changeBy->fullname,
0 ignored issues
show
Documentation introduced by
The property fullname does not exist on object<Tinyissue\Model\Project\User>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
252
        ];
253 4
        if ($this->getIssue()) {
254 3
            $messageData['changes']['change_by']['url'] = $this->getIssue()->to();
255
        } else {
256 1
            $messageData['changes']['change_by']['url'] = $this->getProject()->to();
257
        }
258 4
        $messageData['changeByImage']   = $queue->changeBy->image;
0 ignored issues
show
Documentation introduced by
The property image does not exist on object<Tinyissue\Model\Project\User>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
259 4
        $messageData['changeByHeading'] = $this->getMessageHeading($queue);
260 4
        $messageData['event']           = $queue->event;
261
262
        // Info specific to a message type
263 4
        $method = 'getMessageDataFor' . ucfirst(camel_case($queue->event));
264 4
        if (method_exists($this, $method)) {
265 4
            $messageData = array_replace_recursive($messageData, $this->{$method}($queue, $extraData));
266
        }
267
268 4
        return $messageData;
269
    }
270
271
    /**
272
     * Loop through all of the messages and combine its message data.
273
     *
274
     * @param Collection $changes
275
     *
276
     * @return array
277
     */
278 4
    protected function getCombineMessageData(Collection $changes)
279
    {
280 4
        $everything = [];
281
        $changes->reverse()->each(function (Message\Queue $queue) use (&$everything) {
282 4
            if (!$everything) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $everything of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
283 4
                $everything = $this->getMessageData($queue);
284
            } else {
285 4
                $messageData = $this->getMessageData($queue);
286 4
                $everything['changes'] = array_merge($everything['changes'], $messageData['changes']);
287
            }
288 4
        });
289 4
        $latestMessage                 = $changes->first();
290 4
        $everything['changeByHeading'] = $this->getMessageHeading($latestMessage, $changes);
291 4
        $everything['event']           = $latestMessage->event;
292 4
        $messageData                   = $this->getMessageData($latestMessage);
293 4
        $everything = array_replace_recursive($everything, $messageData);
294
295 4
        return $everything;
296
    }
297
298
    /**
299
     * Return text to be used for the message heading.
300
     *
301
     * @param Message\Queue   $queue
302
     * @param Collection|null $changes
303
     *
304
     * @return string
305
     */
306 4
    protected function getMessageHeading(Message\Queue $queue, Collection $changes = null)
307
    {
308 4
        $heading = $queue->changeBy->fullname . ' ';
0 ignored issues
show
Documentation introduced by
The property fullname does not exist on object<Tinyissue\Model\Project\User>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
309
310
        // If other users have made changes too
311 4
        if (!is_null($changes) && $changes->unique('change_by_id')->count() > 1) {
312 1
            $heading .= '& others ';
313
        }
314
315 4
        return $heading;
316
    }
317
318
    /**
319
     * Returns collection of all users in a project that should receive the messages.
320
     *
321
     * @return Collection
322
     */
323 4
    protected function getProjectUsers()
324
    {
325 4
        if (null === $this->projectUsers) {
326 4
            $this->projectUsers = (new Project\User())
327 4
                ->with('message', 'user', 'user.role')
328 4
                ->whereNotIn('user_id', $this->getExcludeUsers()->lists('id'))
329 4
                ->where('project_id', '=', $this->getProjectId())
330 4
                ->get();
331
        }
332
333 4
        return $this->projectUsers;
334
    }
335
336
    /**
337
     * Returns the model that is belong to the queue message.
338
     *
339
     * @return Issue|Issue\Comment|Note
340
     */
341 4
    protected function getModel()
342
    {
343 4
        return $this->latestMessage->model;
0 ignored issues
show
Documentation introduced by
The property model does not exist on object<Tinyissue\Model\Message\Queue>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
344
    }
345
346
    /**
347
     * Returns an instance of project issue.
348
     *
349
     * @return Issue
350
     */
351
    abstract protected function getIssue();
352
353
    /**
354
     * Returns an instance of project.
355
     *
356
     * @return Project
357
     */
358
    abstract protected function getProject();
359
360
    /**
361
     * Returns the id of a project.
362
     *
363
     * @return int
364
     */
365
    abstract protected function getProjectId();
366
367
    /**
368
     * Returns collection of all of the users that must not receive messages.
369
     *
370
     * @return Collection
371
     */
372 4
    protected function getExcludeUsers()
373
    {
374 4
        if (null === $this->excludeUsers) {
375 4
            $this->excludeUsers = collect([]);
376
        }
377
378 4
        return $this->excludeUsers;
379
    }
380
381
    /**
382
     * Exclude a user from receiving messages.
383
     *
384
     * @param User $user
385
     *
386
     * @return $this
387
     */
388 4
    protected function addToExcludeUsers(User $user)
389
    {
390 4
        $this->getExcludeUsers()->push($user);
391
392 4
        return $this;
393
    }
394
395
    /**
396
     * Find user by id. This search the project users and fallback to excluded list of users.
397
     *
398
     * @param int $userId
399
     *
400
     * @return User
401
     */
402 3
    protected function getUserById($userId)
403
    {
404 3
        $projectUser = $this->getProjectUsers()->where('user_id', $userId, false)->first();
405
406 3
        if (!$projectUser) {
407 3
            return $this->getExcludeUsers()->where('id', $userId, false)->first();
408
        }
409
410 3
        return $projectUser->user;
411
    }
412
413
    /**
414
     * Returns collection of all messages.
415
     *
416
     * @return Collection
417
     */
418 4
    protected function getMessages()
419
    {
420 4
        if (null === $this->messages) {
421 4
            $this->messages = (new Message())->orderBy('id', 'ASC')->get();
0 ignored issues
show
Documentation Bug introduced by
The method orderBy does not exist on object<Tinyissue\Model\Message>? 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...
422
        }
423
424 4
        return $this->messages;
425
    }
426
427
    /**
428
     * Send a message to a user.
429
     *
430
     * @param User  $user
431
     * @param array $data
432
     *
433
     * @return mixed
434
     */
435 4
    private function sendMessage(User $user, array $data)
436
    {
437
        // Make sure the data contains changes
438 4
        if (!array_key_exists('changes', $data) && count($data['changes']) > 1) {
439
            return;
440
        }
441
442 4
        return $this->mailer->send('email.' . $this->template, $data, function (MailMessage $message) use ($user) {
443 4
            $message->to($user->email, $user->fullname)->subject($this->getSubject());
444 4
        });
445
    }
446
447
    /**
448
     * Send a message to a collection of users, or send customised message per use logic.
449
     *
450
     * @param Collection $users
451
     * @param array      $data
452
     *
453
     * @return void
454
     */
455 4
    protected function sendMessages(Collection $users, array $data)
456
    {
457 4
        foreach ($users as $user) {
458 4
            $userMessageData = $this->getUserMessageData($user->user_id, $data);
459 4
            if (!$this->wantToReceiveMessage($user, $userMessageData)) {
460 4
                continue;
461
            }
462
463 4
            $this->sendMessage($user->user, $userMessageData);
464
        }
465 4
    }
466
467
    /**
468
     * Get customised message per user logic.
469
     *
470
     * @param int  $userId
471
     * @param array $messagesData
472
     *
473
     * @return array
474
     */
475 4
    protected function getUserMessageData($userId, array $messagesData)
476
    {
477 4
        if (array_key_exists('event', $messagesData)) {
478 4
            return $messagesData;
479
        }
480
481
        // Possible message data
482 4
        $addMessageData        = $messagesData['addMessage'];
483 4
        $everythingMessageData = $messagesData['everything'];
484
485
        // Check if the user has seen the model data and made a change
486 4
        $changeMadeByUser = $this->allMessages->where('change_by_id', $userId);
487
488
        // This user has never seen this model data
489 4
        if (!$changeMadeByUser->count()) {
490 4
            if ($this->addMessage) {
491 4
                return $addMessageData;
492
            }
493
494 3
            return $everythingMessageData;
495
        }
496
497
        // This user has seen this model data
498
        // Get all of the changes that may happened later.
499
        // Combine them and send message to the user about these changes.
500 1
        $everythingMessageData = $this->getCombineMessageData(
501 1
            $this->allMessages->forget($changeMadeByUser->keys()->toArray())
502
        );
503
504 1
        return $everythingMessageData;
505
    }
506
507
    /**
508
     * Whether or not the user wants to receive the message.
509
     *
510
     * @param Project\User $user
511
     * @param array        $data
512
     *
513
     * @return bool
514
     */
515 4
    protected function wantToReceiveMessage(Project\User $user, array $data)
516
    {
517
        /** @var Message $message */
518 4
        $message = $user->message;
0 ignored issues
show
Bug introduced by
The property message does not seem to exist. Did you mean message_id?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
519 4
        if (!$message) {
520 4
            $roleName = $user->user->role->role;
0 ignored issues
show
Documentation introduced by
The property user does not exist on object<Tinyissue\Model\Project\User>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
521 4
            $message  = $this->getMessages()->where('name', Message::$defaultMessageToRole[$roleName])->first();
522
        }
523
524
        // No message to send,
525
        // - if we can't find message object or
526
        // - messages are disabled or
527
        // - event is inactive for the user message setting
528 4
        if (!$message || $message->isDisabled() || !$message->isActiveEvent($data['event'])) {
529 4
            return false;
530
        }
531
532
        // Wants to see all updates in project
533 4
        if ((bool) $message->in_all_issues === true) {
534 4
            return true;
535
        }
536
537 4
        if (!$this->getIssue()) {
538 1
            return false;
539
        }
540
541
        // For issue only send messages if user is assignee or creator
542 3
        $creator  = $this->getIssue()->user;
543 3
        $assignee = $this->getIssue()->assigned;
0 ignored issues
show
Bug introduced by
The property assigned does not seem to exist. Did you mean assigned_to?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
544 3
        if ($user->user_id === $creator->id || ($assignee && $user->user_id === $assignee->id)) {
545 2
            return true;
546
        }
547
548 3
        return false;
549
    }
550
551
    /**
552
     * Send a message to al users in project and full subscribes.
553
     *
554
     * @param Message\Queue $queue
555
     *
556
     * @return void
557
     */
558 4
    protected function sendMessageToAll(Message\Queue $queue)
559
    {
560 4
        $messageData = $this->getMessageData($queue);
561
562 4
        $this->sendMessages($this->getProjectUsers(), $messageData);
563 4
    }
564
565
    /**
566
     * Load the creator of an issue to the collection of project users. So we can send message to creator if needed.
567
     *
568
     * @return void
569
     */
570 3
    protected function loadIssueCreatorToProjectUsers()
571
    {
572
        // Stop if we can't get the issue
573 3
        if (!$this->getIssue()) {
574
            return;
575
        }
576
577
        // Get issue creator
578 3
        $creator = $this->getIssue()->user;
579
580
        // Stop if creator excluded from messages
581 3
        $excluded = $this->getExcludeUsers()->where('id', $creator->id, false)->first();
582 3
        if ($excluded) {
583 3
            return;
584
        }
585
586
        // Stop if the creator already part of the project users
587 3
        $existInProject = $this->getProjectUsers()->where('user_id', $creator->id, false)->first();
588 3
        if ($existInProject) {
589 3
            return;
590
        }
591
592
        // Create virtual project user object & add to collection
593
        $userProject = new Project\User([
594
            'user_id'    => $creator->id,
595
            'project_id' => $this->getProjectId(),
596
        ]);
597
        $userProject->setRelation('user', $creator);
598
        $userProject->setRelation('project', $this->getProject());
599
        $this->getProjectUsers()->push($userProject);
600
    }
601
}
602