Completed
Branch master (8e0976)
by Adam
04:13
created

SubmitController::index()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 4
nop 4
dl 0
loc 21
rs 8.9617
c 0
b 0
f 0
1
<?php
2
3
namespace Coyote\Http\Controllers\Forum;
4
5
use Coyote\Http\Controllers\Controller;
6
use Coyote\Http\Forms\Forum\SubjectForm;
7
use Coyote\Notifications\Post\ChangedNotification;
8
use Coyote\Notifications\Post\SubmittedNotification;
9
use Coyote\Notifications\Post\UserMentionedNotification;
10
use Coyote\Notifications\Topic\SubjectChangedNotification;
11
use Coyote\Repositories\Contracts\PollRepositoryInterface;
12
use Coyote\Repositories\Contracts\UserRepositoryInterface;
13
use Coyote\Services\UrlBuilder\UrlBuilder;
14
use Illuminate\Contracts\Notifications\Dispatcher;
15
use Illuminate\Http\Request;
16
use Coyote\Services\Stream\Activities\Create as Stream_Create;
17
use Coyote\Services\Stream\Activities\Update as Stream_Update;
18
use Coyote\Services\Stream\Objects\Topic as Stream_Topic;
19
use Coyote\Services\Stream\Objects\Post as Stream_Post;
20
use Coyote\Services\Stream\Objects\Forum as Stream_Forum;
21
use Coyote\Services\Stream\Actor as Stream_Actor;
22
use Coyote\Services\Parser\Helpers\Login as LoginHelper;
23
use Coyote\Events\PostWasSaved;
24
use Coyote\Events\TopicWasSaved;
25
use Coyote\Post\Log;
26
27
class SubmitController extends BaseController
28
{
29
    /**
30
     * Show new post/edit form
31
     *
32
     * @param Request $request
33
     * @param \Coyote\Forum $forum
34
     * @param \Coyote\Topic $topic
35
     * @param \Coyote\Post|null $post
36
     * @return \Illuminate\View\View
37
     */
38
    public function index(Request $request, $forum, $topic, $post = null)
39
    {
40
        if (!empty($topic->id)) {
41
            $this->breadcrumb->push([
42
                $topic->subject => route('forum.topic', [$forum->slug, $topic->id, $topic->slug]),
43
                $post === null ? 'Odpowiedz' : 'Edycja' => url($request->path())
44
            ]);
45
        } else {
46
            $this->breadcrumb->push('Nowy wątek', route('forum.topic.submit', [$forum->slug]));
47
        }
48
49
        if (!empty($post)) {
50
            // make sure user can edit this post
51
            $this->authorize('update', [$post]);
52
        }
53
54
        $form = $this->getForm($forum, $topic, $post);
55
        $form->text->setValue($form->text->getValue() ?: ($topic ? $this->getDefaultText($request, $topic) : ''));
0 ignored issues
show
Documentation introduced by
The property text does not exist on object<Coyote\Http\Forms\Forum\PostForm>. 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...
56
57
        return Controller::view('forum.submit')->with(compact('forum', 'form', 'topic', 'post'));
58
    }
59
60
    /**
61
     * Show new post/edit form
62
     *
63
     * @param Dispatcher $dispatcher
64
     * @param \Coyote\Forum $forum
65
     * @param \Coyote\Topic $topic
66
     * @param \Coyote\Post|null $post
67
     * @return mixed
68
     */
69
    public function save(Dispatcher $dispatcher, $forum, $topic, $post = null)
70
    {
71
        if (is_null($post)) {
72
            $post = $this->post->makeModel();
73
        } else {
74
            $this->authorize('update', [$post]);
75
        }
76
77
        $form = $this->getForm($forum, $topic, $post);
78
        $form->validate();
79
80
        $request = $form->getRequest();
81
82
        $post = $this->transaction(function () use ($form, $forum, $topic, $post, $request) {
83
            $actor = new Stream_Actor($this->auth);
84
            if (auth()->guest()) {
85
                $actor->displayName = $request->get('user_name');
86
            }
87
88
            $poll = $this->savePoll($request, $topic->poll_id);
89
90
            $activity = $post->id ? new Stream_Update($actor) : new Stream_Create($actor);
91
            // saving post through repository... we need to pass few object to save relationships
92
            $this->post->save($form, $this->auth, $forum, $topic, $post, $poll);
93
94
            // url to the post
95
            $url = UrlBuilder::post($post);
96
97
            if ($topic->wasRecentlyCreated || $post->id === $topic->first_post_id) {
98
                $object = (new Stream_Topic)->map($topic, $post->html);
99
                $target = (new Stream_Forum)->map($forum);
100
            } else {
101
                $object = (new Stream_Post(['url' => $url]))->map($post);
102
                $target = (new Stream_Topic())->map($topic);
103
            }
104
105
            stream($activity, $object, $target);
106
107
            $request->attributes->set('url', $url);
108
109
            return $post;
110
        });
111
112
        if ($post->wasRecentlyCreated) {
113
            $subscribers = $topic->subscribers()->with('user')->get()->pluck('user')->exceptUser($this->auth);
114
115
            $dispatcher->send(
116
                $subscribers,
117
                (new SubmittedNotification($this->auth, $post))->setSender($request->get('user_name'))
118
            );
119
120
            // get id of users that were mentioned in the text
121
            $usersId = (new LoginHelper())->grab($post->html);
122
123 View Code Duplication
            if (!empty($usersId)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
124
                $dispatcher->send(
125
                    app(UserRepositoryInterface::class)->findMany($usersId)->exceptUser($this->auth)->exceptUsers($subscribers),
126
                    (new UserMentionedNotification($this->auth, $post))->setSender($request->get('user_name'))
127
                );
128
            }
129
        } else {
130
            $subscribers = $post->subscribers()->with('user')->get()->pluck('user')->exceptUser($this->auth);
131
132
            $dispatcher->send(
133
                $subscribers,
134
                new ChangedNotification($this->auth, $post)
135
            );
136
        }
137
138
        // fire the event. it can be used to index a content and/or add page path to "pages" table
139
        event(new TopicWasSaved($topic));
140
        // add post to elasticsearch
141
        event(new PostWasSaved($post));
142
143
        return $post;
144
    }
145
146
    /**
147
     * @param Request $request
148
     * @param int $pollId
149
     * @return \Coyote\Poll|null
150
     */
151
    private function savePoll(Request $request, $pollId)
152
    {
153
        if ($request->input('poll.remove')) {
154
            $this->getPollRepository()->delete($pollId);
155
        } elseif ($request->filled('poll.title')) {
156
            return $this->getPollRepository()->updateOrCreate($pollId, $request->input('poll'));
157
        } elseif ($pollId) {
158
            return $this->getPollRepository()->find($pollId);
159
        }
160
161
        return null;
162
    }
163
164
    /**
165
     * @return PollRepositoryInterface
166
     */
167
    private function getPollRepository()
168
    {
169
        return app(PollRepositoryInterface::class);
170
    }
171
172
    /**
173
     * Ajax request. Display edit form
174
     *
175
     * @param $forum
176
     * @param $topic
177
     * @param $post
178
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
179
     */
180
    public function edit($forum, $topic, $post)
181
    {
182
        $this->authorize('update', [$post]);
183
        $form = $this->getForm($forum, $topic, $post);
184
185
        return view('forum.partials.edit')->with('form', $form);
186
    }
187
188
    /**
189
     * @param \Coyote\Topic $topic
190
     * @param SubjectForm $form
191
     * @return \Symfony\Component\HttpFoundation\Response
192
     *
193
     * @todo moze jakas refaktoryzacja? przeniesienie do repozytorium? na pewno logowanie o tym, ze zostal zmieniony
194
     * tytul a nie tresc posta (jak to jest obecnie)
195
     */
196
    public function subject($topic, SubjectForm $form)
197
    {
198
        /** @var \Coyote\Forum $forum */
199
        $forum = $topic->forum()->first();
200
        $this->authorize('update', $forum);
201
202
        $request = $form->getRequest();
203
204
        $url = $this->transaction(function () use ($request, $forum, $topic) {
205
            $topic->fill(['subject' => $request->get('subject')]);
206
207
            /** @var \Coyote\Post $post */
208
            $post = $topic->firstPost()->first();
209
            $url = route('forum.topic', [$forum->slug, $topic->id, $topic->slug], false);
210
211
            if ($topic->isDirty()) {
212
                $original = $topic->getOriginal();
213
214
                $topic->save();
215
                $tags = $topic->getTagNames();
216
217
                // save it in log...
218
                (new Log)
219
                    ->fillWithPost($post)
220
                    ->fill(['user_id' => $this->userId, 'subject' => $topic->subject, 'tags' => $tags])
221
                    ->save();
222
223
                $post->fill([
224
                    'edit_count' => $post->edit_count + 1, 'editor_id' => $this->userId
225
                ])
226
                ->save();
227
228
                if ($post->user_id !== null) {
229
                    $post->user->notify(
230
                        (new SubjectChangedNotification($this->auth, $topic))
231
                            ->setOriginalSubject(str_limit($original['subject'], 84))
232
                    );
233
                }
234
235
                // fire the event. it can be used to index a content and/or add page path to "pages" table
236
                event(new TopicWasSaved($topic));
237
                // add post to elasticsearch
238
                event(new PostWasSaved($post));
239
            }
240
241
            // get text from cache to put excerpt in stream activity
242
            $post->text = app('parser.post')->parse($post->text);
243
244
            // put action into activity stream
245
            stream(
246
                Stream_Update::class,
247
                (new Stream_Topic)->map($topic, $post->text),
248
                (new Stream_Forum)->map($forum)
249
            );
250
251
            return $url;
252
        });
253
254
        if ($request->ajax()) {
255
            return response(url($url));
0 ignored issues
show
Bug introduced by
It seems like url($url) targeting url() can also be of type object<Illuminate\Contracts\Routing\UrlGenerator>; however, response() does only seem to accept string|object<Illuminate\View\View>|array|null, 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...
256
        } else {
257
            return redirect()->to($url);
258
        }
259
    }
260
261
    /**
262
     * Format post text in case of quoting
263
     *
264
     * @param Request $request
265
     * @param \Coyote\Topic $topic
266
     * @return string
267
     */
268
    protected function getDefaultText(Request $request, $topic)
269
    {
270
        $text = '';
271
272
        // IDs of posts that user want to quote...
273
        $postsId = [];
274
        $cookie = isset($_COOKIE['mqid' . $topic->id]) ? $_COOKIE['mqid' . $topic->id] : null;
275
276
        if ($cookie) {
277
            $postsId = array_map('intval', explode(',', $cookie));
278
            // I used raw PHP function because I don't want to use laravel encryption in this case
279
            setcookie('mqid' . $topic->id, null, time() - 3600, '/');
280
        }
281
282
        if ($request->input('quote')) {
283
            $postsId[] = intval($request->input('quote'));
284
        }
285
286
        if (!empty($postsId)) {
287
            $posts = $this->post->findPosts(array_unique($postsId), $topic->id);
288
289
            // builds text with quoted posts
290
            foreach ($posts as $post) {
291
                $text .= '> ##### [' .
292
                    ($post->name ?: $post->user_name) .
293
                    ' napisał(a)](' . route('forum.share', [$post->id]) . '):';
294
295
                $text .= "\n> " . str_replace("\n", "\n> ", $post->text);
296
                $text .= "\n\n";
297
            }
298
        }
299
300
        return $text;
301
    }
302
}
303