DefaultController   A
last analyzed

Complexity

Total Complexity 39

Size/Duplication

Total Lines 532
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 39
eloc 242
c 1
b 0
f 0
dl 0
loc 532
rs 9.28

8 Methods

Rating   Name   Duplication   Size   Complexity  
B forumCreatePost() 0 83 8
B forumCreateThread() 0 96 8
B forumAdmin() 0 56 9
A index() 0 10 1
A forumBoard() 0 60 3
A newForum() 0 46 5
A forumThread() 0 60 3
A forumIndex() 0 20 2
1
<?php
2
3
namespace App\Controller;
4
5
use App\Entity\Board;
6
use App\Entity\Forum;
7
use App\Entity\Post;
8
use App\Entity\Thread;
9
use App\Entity\User;
10
use App\Form\NewForumType;
11
use App\Form\PostType;
12
use App\Form\ThreadType;
13
use App\Service\AdminControlPanel;
14
use App\Service\ForumHelper;
15
use DateTime;
16
use Exception;
17
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
18
use Symfony\Component\Form\FormError;
19
use Symfony\Component\HttpFoundation\RedirectResponse;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpFoundation\Response;
22
use Symfony\Component\HttpKernel\KernelInterface;
23
use Symfony\Component\Routing\Annotation\Route;
24
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
25
use Symfony\Component\Security\Core\User\UserInterface;
26
use Symfony\Contracts\Translation\TranslatorInterface;
27
28
class DefaultController extends AbstractController
29
{
30
    /**
31
     * @Route("/", name="index")
32
     *
33
     * @return Response
34
     */
35
    public function index()
36
    {
37
        $em = $this->getDoctrine()->getManager();
38
        /** @var Forum[] $forumList */
39
        $forumList = $em->getRepository(Forum::class)->findAll();
40
41
        return $this->render(
42
            'list-forums.html.twig',
43
            [
44
                'forums_list' => $forumList,
45
            ]
46
        );
47
    }
48
49
    /**
50
     * @Route("/new-forum", name="new")
51
     *
52
     * @param Request             $request    The request
53
     * @param TranslatorInterface $translator The translator
54
     *
55
     * @return RedirectResponse|Response
56
     */
57
    public function newForum(Request $request, TranslatorInterface $translator)
58
    {
59
        //////////// TEST IF USER IS LOGGED IN ////////////
60
        /** @var User|null $user */
61
        $user = $this->getUser();
62
        if (!$user instanceof UserInterface) {
63
            throw $this->createAccessDeniedException();
64
        }
65
        //////////// END TEST IF USER IS LOGGED IN ////////////
66
67
        $createForumForm = $this->createForm(NewForumType::class);
68
69
        $createForumForm->handleRequest($request);
70
        if ($createForumForm->isSubmitted() && $createForumForm->isValid()) {
71
            $formData = $createForumForm->getData();
72
73
            try {
74
                $newForum = new Forum();
75
                $newForum
76
                    ->setName($formData['name'])
77
                    ->setUrl($formData['url'])
78
                    ->setOwner($user)
79
                    ->setCreated(new DateTime())
80
                ;
81
                $em = $this->getDoctrine()->getManager();
82
                $em->persist($newForum);
83
                $em->flush();
84
85
                return $this->redirectToRoute('forum_index', ['forum' => $newForum->getUrl()]);
86
            } catch (Exception $e) {
87
                $createForumForm->addError(
88
                    new FormError(
89
                        $translator->trans(
90
                            'new_forum.not_created',
91
                            ['%error_message%' => $e->getMessage()],
92
                            'validators'
93
                        )
94
                    )
95
                );
96
            }
97
        }
98
99
        return $this->render(
100
            'create-new-forum.html.twig',
101
            [
102
                'create_forum_form' => $createForumForm->createView(),
103
            ]
104
        );
105
    }
106
107
    /**
108
     * @Route("/{forum}", name="forum_index")
109
     *
110
     * @param string $forum The forum
111
     *
112
     * @return Response
113
     */
114
    public function forumIndex(string $forum)
115
    {
116
        //////////// TEST IF FORUM EXISTS ////////////
117
        $em = $this->getDoctrine()->getManager();
118
        /** @var Forum|null $forum */
119
        $forum = $em->getRepository(Forum::class)->findOneBy(['url' => $forum]);
120
        if (null === $forum) {
121
            throw $this->createNotFoundException();
122
        }
123
        //////////// END TEST IF FORUM EXISTS ////////////
124
125
        // Get all boards
126
        /** @var Board[] $boardTree */
127
        $boardTree = $em->getRepository(Board::class)->findBy(['forum' => $forum, 'parent_board' => null]);
128
129
        return $this->render(
130
            'theme1/index.html.twig',
131
            [
132
                'current_forum' => $forum,
133
                'board_tree' => $boardTree,
134
            ]
135
        );
136
    }
137
138
    /**
139
     * @Route("/{forum}/board/{board}", name="forum_board")
140
     *
141
     * @param Request     $request The request
142
     * @param ForumHelper $helper  The forum helper
143
     * @param string      $forum   The forum
144
     * @param string      $board   The board
145
     *
146
     * @return Response
147
     */
148
    public function forumBoard(Request $request, ForumHelper $helper, string $forum, string $board)
149
    {
150
        //////////// TEST IF FORUM EXISTS ////////////
151
        $em = $this->getDoctrine()->getManager();
152
        /** @var Forum|null $forum */
153
        $forum = $em->getRepository(Forum::class)->findOneBy(['url' => $forum]);
154
        if (null === $forum) {
155
            throw $this->createNotFoundException();
156
        }
157
        //////////// END TEST IF FORUM EXISTS ////////////
158
159
        //////////// TEST IF BOARD EXISTS ////////////
160
        /** @var Board|null $board */
161
        $board = $em->getRepository(Board::class)->findOneBy(['id' => $board]);
162
        if (null === $board) {
163
            throw $this->createNotFoundException();
164
        }
165
        //////////// TEST IF BOARD EXISTS ////////////
166
167
        // Breadcrumb
168
        $breadcrumb = $helper->getBreadcrumb($board);
169
170
        // Get all boards
171
        $boardTree = $em->getRepository(Board::class)->findBy(['forum' => $forum, 'parent_board' => $board]);
172
173
        // Get all threads
174
        $pagination = [];
175
        $pagination['item_limit'] = $request->query->getInt('show', ForumHelper::DEFAULT_SHOW_THREAD_COUNT);
176
        $pagination['current_page'] = $request->query->getInt('page', 1);
177
178
        /** @var Thread[] $threads */
179
        $threads = $em->getRepository(Thread::class)->findBy(
180
            ['board' => $board],
181
            ['last_post_time' => 'DESC'],
182
            $pagination['item_limit'],
183
            ($pagination['current_page'] - 1) * $pagination['item_limit']
184
        )
185
        ;
186
187
        // Pagination
188
        // Reference: http://www.strangerstudios.com/sandbox/pagination/diggstyle.php
189
        /** @var Thread[] $threadCount */
190
        $threadCount = $em->getRepository(Thread::class)->findBy(['board' => $board]);
191
        $pagination['total_items'] = count($threadCount);
192
        $pagination['adjacents'] = 1;
193
194
        $pagination['next_page'] = $pagination['current_page'] + 1;
195
        $pagination['previous_page'] = $pagination['current_page'] - 1;
196
        $pagination['pages_count'] = ceil($pagination['total_items'] / $pagination['item_limit']);
197
        $pagination['last_page_m1'] = $pagination['pages_count'] - 1;
198
199
        return $this->render(
200
            'theme1/board.html.twig',
201
            [
202
                'current_forum' => $forum,
203
                'current_board' => $board,
204
                'breadcrumb' => $breadcrumb,
205
                'board_tree' => $boardTree,
206
                'threads' => $threads,
207
                'pagination' => $pagination,
208
            ]
209
        );
210
    }
211
212
    /**
213
     * @Route("/{forum}/thread/{thread}", name="forum_thread")
214
     *
215
     * @param Request     $request The request
216
     * @param ForumHelper $helper  The forum helper
217
     * @param string      $forum   The forum
218
     * @param string      $thread  The thread
219
     *
220
     * @return Response
221
     */
222
    public function forumThread(Request $request, ForumHelper $helper, string $forum, string $thread)
223
    {
224
        //////////// TEST IF FORUM EXISTS ////////////
225
        $em = $this->getDoctrine()->getManager();
226
        /** @var Forum|null $forum */
227
        $forum = $em->getRepository(Forum::class)->findOneBy(['url' => $forum]);
228
        if (null === $forum) {
229
            throw $this->createNotFoundException();
230
        }
231
        //////////// END TEST IF FORUM EXISTS ////////////
232
233
        //////////// TEST IF THREAD EXISTS ////////////
234
        /** @var Thread|null $thread */
235
        $thread = $em->getRepository(Thread::class)->findOneBy(['id' => $thread]);
236
        if (null === $thread) {
237
            throw $this->createNotFoundException();
238
        }
239
        $thread->setViews($thread->getViews() + 1);
240
        $em->flush();
241
242
        $board = $thread->getBoard();
243
        //////////// END TEST IF THREAD EXISTS ////////////
244
245
        // Breadcrumb
246
        $breadcrumb = $helper->getBreadcrumb($board);
247
248
        // Get all posts
249
        $pagination = [];
250
        $pagination['item_limit'] = $request->query->getInt('show', ForumHelper::DEFAULT_SHOW_THREAD_COUNT);
251
        $pagination['current_page'] = $request->query->getInt('page', 1);
252
253
        /** @var Post[] $posts */
254
        $posts = $em->getRepository(Post::class)->findBy(
255
            ['thread' => $thread],
256
            ['post_number' => 'ASC'],
257
            $pagination['item_limit'],
258
            ($pagination['current_page'] - 1) * $pagination['item_limit']
259
        )
260
        ;
261
262
        // Pagination
263
        /** @var Post[] $postCount */
264
        $postCount = $em->getRepository(Post::class)->findBy(['thread' => $thread]);
265
        $pagination['total_items'] = count($postCount);
266
        $pagination['adjacents'] = 1;
267
268
        $pagination['next_page'] = $pagination['current_page'] + 1;
269
        $pagination['previous_page'] = $pagination['current_page'] - 1;
270
        $pagination['pages_count'] = ceil($pagination['total_items'] / $pagination['item_limit']);
271
        $pagination['last_page_m1'] = $pagination['pages_count'] - 1;
272
273
        return $this->render(
274
            'theme1/thread.html.twig',
275
            [
276
                'current_forum' => $forum,
277
                'current_board' => $board,
278
                'current_thread' => $thread,
279
                'posts' => $posts,
280
                'breadcrumb' => $breadcrumb,
281
                'pagination' => $pagination,
282
            ]
283
        );
284
    }
285
286
    /**
287
     * @Route("/{forum}/thread/{thread}/create-post", name="forum_create_post")
288
     *
289
     * @param Request     $request The request
290
     * @param ForumHelper $helper  The forum helper
291
     * @param string      $forum   The forum
292
     * @param string      $thread  The thread
293
     *
294
     * @return Response
295
     */
296
    public function forumCreatePost(Request $request, ForumHelper $helper, string $forum, string $thread)
297
    {
298
        //////////// TEST IF USER IS LOGGED IN ////////////
299
        /** @var User|null $user */
300
        $user = $this->getUser();
301
        if (!$user instanceof UserInterface) {
302
            throw $this->createAccessDeniedException();
303
        }
304
        //////////// END TEST IF USER IS LOGGED IN ////////////
305
306
        //////////// TEST IF FORUM EXISTS ////////////
307
        $em = $this->getDoctrine()->getManager();
308
        /** @var Forum|null $forum */
309
        $forum = $em->getRepository(Forum::class)->findOneBy(['url' => $forum]);
310
        if (null === $forum) {
311
            throw $this->createNotFoundException();
312
        }
313
        //////////// END TEST IF FORUM EXISTS ////////////
314
315
        //////////// TEST IF THREAD EXISTS ////////////
316
        /** @var Thread|null $thread */
317
        $thread = $em->getRepository(Thread::class)->findOneBy(['id' => $thread]);
318
        if (null === $thread) {
319
            throw $this->createNotFoundException();
320
        }
321
322
        $board = $thread->getBoard();
323
        //////////// END TEST IF THREAD EXISTS ////////////
324
325
        // Breadcrumb
326
        $breadcrumb = $helper->getBreadcrumb($board);
327
328
        $createPostForm = $this->createForm(PostType::class, null, ['topic' => $thread->getTopic()]);
329
330
        $createPostForm->handleRequest($request);
331
        if ($createPostForm->isSubmitted() && $createPostForm->isValid()) {
332
            $formData = $createPostForm->getData();
333
334
            try {
335
                $time = new DateTime();
336
337
                // Add post entity
338
                $newPost = new Post();
339
                $newPost
340
                    ->setThread($thread)
341
                    ->setUser($user)
342
                    ->setPostNumber($thread->getReplies() + 2)
343
                    ->setSubject($formData['title'])
344
                    ->setMessage($formData['message'])
345
                    ->setCreatedOn($time)
346
                ;
347
                $em->persist($newPost);
348
349
                // Update thread count and last post user and time
350
                $thread->setReplies($thread->getReplies() + 1);
351
                $thread->setLastPostUser($user);
352
                $thread->setLastPostTime($time);
353
354
                $board->setPostCount($board->getPostCount() + 1);
355
                $board->setLastPostUser($user);
356
                $board->setLastPostTime($time);
357
                foreach ($breadcrumb as $item) {
358
                    $item->setPostCount($item->getPostCount() + 1);
359
                    $item->setLastPostUser($user);
360
                    $item->setLastPostTime($time);
361
                }
362
363
                $em->flush();
364
365
                $this->addFlash('post_created', '');
366
            } catch (Exception $e) {
367
                $this->addFlash('post_not_created', '');
368
            }
369
        }
370
371
        return $this->render(
372
            'theme1/create-post.html.twig',
373
            [
374
                'current_forum' => $forum,
375
                'current_board' => $board,
376
                'current_thread' => $thread,
377
                'breadcrumb' => $breadcrumb,
378
                'create_post_form' => $createPostForm->createView(),
379
            ]
380
        );
381
    }
382
383
    /**
384
     * @Route("/{forum}/board/{board}/create-thread", name="forum_create_thread")
385
     *
386
     * @param Request     $request The request
387
     * @param ForumHelper $helper  The forum helper
388
     * @param string      $forum   The forum
389
     * @param string      $board   The board
390
     *
391
     * @return Response
392
     */
393
    public function forumCreateThread(Request $request, ForumHelper $helper, string $forum, string $board)
394
    {
395
        //////////// TEST IF USER IS LOGGED IN ////////////
396
        /** @var User|null $user */
397
        $user = $this->getUser();
398
        if (!$user instanceof UserInterface) {
399
            throw $this->createAccessDeniedException();
400
        }
401
        //////////// END TEST IF USER IS LOGGED IN ////////////
402
403
        //////////// TEST IF FORUM EXISTS ////////////
404
        $em = $this->getDoctrine()->getManager();
405
        /** @var Forum|null $forum */
406
        $forum = $em->getRepository(Forum::class)->findOneBy(['url' => $forum]);
407
        if (null === $forum) {
408
            throw $this->createNotFoundException();
409
        }
410
        //////////// END TEST IF FORUM EXISTS ////////////
411
412
        //////////// TEST IF BOARD EXISTS ////////////
413
        /** @var Board|null $board */
414
        $board = $em->getRepository(Board::class)->findOneBy(['id' => $board]);
415
        if (null === $board) {
416
            throw $this->createNotFoundException();
417
        }
418
        //////////// TEST IF BOARD EXISTS ////////////
419
420
        // Breadcrumb
421
        $breadcrumb = $helper->getBreadcrumb($board);
422
423
        $createThreadForm = $this->createForm(ThreadType::class);
424
425
        $createThreadForm->handleRequest($request);
426
        if ($createThreadForm->isSubmitted() && $createThreadForm->isValid()) {
427
            $formData = $createThreadForm->getData();
428
429
            try {
430
                // Add thread and post entity
431
                $time = new DateTime();
432
                $newThread = new Thread();
433
                $newThread
434
                    ->setUser($user)
435
                    ->setBoard($board)
436
                    ->setTopic($formData['title'])
437
                    ->setCreatedOn($time)
438
                    ->setLastPostUser($user)
439
                    ->setLastPostTime($time)
440
                ;
441
                $newPost = new Post();
442
                $newPost
443
                    ->setUser($user)
444
                    ->setPostNumber(1)
445
                    ->setSubject($formData['title'])
446
                    ->setMessage($formData['message'])
447
                    ->setCreatedOn($time)
448
                ;
449
                $newThread->addPost($newPost);
450
                $em->persist($newThread);
451
                $em->persist($newPost);
452
453
                // Update thread count and last post user and time
454
                $board->setThreadCount($board->getThreadCount() + 1);
455
                $board->setLastPostUser($user);
456
                $board->setLastPostTime($time);
457
                foreach ($breadcrumb as $item) {
458
                    $item->setThreadCount($item->getThreadCount() + 1);
459
                    $item->setLastPostUser($user);
460
                    $item->setLastPostTime($time);
461
                }
462
463
                $em->flush();
464
465
                $this->addFlash('thread_created', '');
466
467
                return $this->render(
468
                    'theme1/create-thread.html.twig',
469
                    [
470
                        'current_forum' => $forum,
471
                        'current_board' => $board,
472
                        'breadcrumb' => $breadcrumb,
473
                        'new_thread_id' => $newThread->getId(),
474
                        'create_thread_form' => $createThreadForm->createView(),
475
                    ]
476
                );
477
            } catch (Exception $e) {
478
                $this->addFlash('thread_not_created', '');
479
            }
480
        }
481
482
        return $this->render(
483
            'theme1/create-thread.html.twig',
484
            [
485
                'current_forum' => $forum,
486
                'current_board' => $board,
487
                'breadcrumb' => $breadcrumb,
488
                'create_thread_form' => $createThreadForm->createView(),
489
            ]
490
        );
491
    }
492
493
    /**
494
     * @Route("/{forum}/admin/{page}", name="forum_admin")
495
     *
496
     * @param KernelInterface       $kernel       The kernel
497
     * @param TokenStorageInterface $tokenStorage The token storage
498
     * @param Request               $request      The request
499
     * @param string                $forum        The forum
500
     * @param string                $page         The page
501
     *
502
     * @return Response
503
     */
504
    public function forumAdmin(
505
        KernelInterface $kernel,
506
        TokenStorageInterface $tokenStorage,
507
        Request $request,
508
        string $forum,
509
        string $page
510
    ) {
511
        //////////// TEST IF USER IS LOGGED IN ////////////
512
        /** @var User|null $user */
513
        $user = $this->getUser();
514
        if (!$user instanceof UserInterface) {
515
            throw $this->createAccessDeniedException();
516
        }
517
        //////////// END TEST IF USER IS LOGGED IN ////////////
518
519
        //////////// TEST IF FORUM EXISTS ////////////
520
        $em = $this->getDoctrine()->getManager();
521
        /** @var Forum|null $forum */
522
        $forum = $em->getRepository(Forum::class)->findOneBy(['url' => $forum]);
523
        if (null === $forum) {
524
            throw $this->createNotFoundException();
525
        }
526
        //////////// END TEST IF FORUM EXISTS ////////////
527
528
        if ($user->getId() !== $forum->getOwner()->getId()) {
529
            throw $this->createAccessDeniedException();
530
        }
531
532
        AdminControlPanel::loadLibs($kernel->getProjectDir(), $tokenStorage);
533
534
        $navigationLinks = AdminControlPanel::getTree();
535
536
        $view = 'DefaultController::notFound';
537
538
        $list = AdminControlPanel::getFlatTree();
539
540
        $key = null;
541
        while ($item = current($list)) {
542
            if (isset($item['href']) && $item['href'] === $page) {
543
                $key = key($list);
544
            }
545
            next($list);
546
        }
547
548
        if (null !== $key) {
549
            if (is_callable('\\App\\Controller\\Panel\\' . $list[$key]['view'])) {
550
                $view = $list[$key]['view'];
551
            }
552
        }
553
554
        return $this->forward(
555
            'App\\Controller\\Panel\\' . $view,
556
            [
557
                'navigation' => $navigationLinks,
558
                'request' => $request,
559
                'forum' => $forum,
560
            ]
561
        );
562
    }
563
}
564