-
-
Notifications
You must be signed in to change notification settings - Fork 834
/
StartDiscussionHandler.php
103 lines (84 loc) · 2.87 KB
/
StartDiscussionHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Discussion\Command;
use Exception;
use Flarum\Discussion\Discussion;
use Flarum\Discussion\DiscussionValidator;
use Flarum\Discussion\Event\Saving;
use Flarum\Foundation\DispatchEventsTrait;
use Flarum\Post\Command\PostReply;
use Illuminate\Contracts\Bus\Dispatcher as BusDispatcher;
use Illuminate\Contracts\Events\Dispatcher as EventDispatcher;
use Illuminate\Support\Arr;
class StartDiscussionHandler
{
use DispatchEventsTrait;
/**
* @var BusDispatcher
*/
protected $bus;
/**
* @var \Flarum\Discussion\DiscussionValidator
*/
protected $validator;
/**
* @param EventDispatcher $events
* @param BusDispatcher $bus
* @param \Flarum\Discussion\DiscussionValidator $validator
*/
public function __construct(EventDispatcher $events, BusDispatcher $bus, DiscussionValidator $validator)
{
$this->events = $events;
$this->bus = $bus;
$this->validator = $validator;
}
/**
* @param StartDiscussion $command
* @return mixed
* @throws Exception
*/
public function handle(StartDiscussion $command)
{
$actor = $command->actor;
$data = $command->data;
$ipAddress = $command->ipAddress;
$actor->assertCan('startDiscussion');
// Create a new Discussion entity, persist it, and dispatch domain
// events. Before persistence, though, fire an event to give plugins
// an opportunity to alter the discussion entity based on data in the
// command they may have passed through in the controller.
$discussion = Discussion::start(
Arr::get($data, 'attributes.title'),
$actor
);
$this->events->dispatch(
new Saving($discussion, $actor, $data)
);
$this->validator->assertValid($discussion->getAttributes());
$discussion->save();
// Now that the discussion has been created, we can add the first post.
// We will do this by running the PostReply command.
try {
$post = $this->bus->dispatch(
new PostReply($discussion->id, $actor, $data, $ipAddress)
);
} catch (Exception $e) {
$discussion->delete();
throw $e;
}
// Before we dispatch events, refresh our discussion instance's
// attributes as posting the reply will have changed some of them (e.g.
// last_time.)
$discussion->setRawAttributes($post->discussion->getAttributes(), true);
$discussion->setFirstPost($post);
$discussion->setLastPost($post);
$this->dispatchEventsFor($discussion, $actor);
$discussion->save();
return $discussion;
}
}