Completed
Push — develop ( 117c72...bb7f99 )
by Victor
03:10
created

BlogController::sortAction()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.3651

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 23
ccs 7
cts 15
cp 0.4667
rs 9.0857
cc 3
eloc 13
nc 3
nop 3
crap 4.3651
1
<?php
2
3
namespace AppBundle\Controller\Blog;
4
5
use AppBundle\Entity\Comment;
6
use AppBundle\Form\Type\CommentType;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
10
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
11
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
12
use Symfony\Component\Form\Extension\Core\Type\EmailType;
13
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
14
use Symfony\Component\Form\Extension\Core\Type\TextType;
15
use Symfony\Component\HttpFoundation\Request;
16
use Symfony\Component\HttpFoundation\Response;
17
use Symfony\Component\Validator\Constraints as Assert;
18
19
class BlogController extends Controller
20
{
21
22
    //ToDo: fix page over limit
23
    /**
24
     * @param $page
25
     * @Method("GET")
26
     * @Route("/{pager}/{page}", name="homepage",
27
     *     defaults={"pager": "page", "page": 1},
28
     *     requirements={
29
     *          "pager": "page",
30
     *          "page": "[1-9]\d*",
31
     *     })
32
     * @Template("AppBundle:blog:blogPosts.html.twig")
33
     *
34
     * @return Response
35
     */
36 1
    public function indexAction($page = 1)
37
    {
38 1
        $em = $this->getDoctrine()->getManager();
39 1
        $articles = $em->getRepository("AppBundle:Article")
40 1
            ->getArticlesWithCountComment($page);
41
42
        return [
43 1
            'articles' => $articles,
44 1
        ];
45
    }
46
47
    /**
48
     * @param $slug
49
     * @Method("GET")
50
     * @Route("/article/{slug}", name="showArticle")
51
     * @Template("AppBundle:blog:blogSingle.html.twig")
52
     *
53
     * @return Response
54
     */
55 1
    public function showAction($slug)
56
    {
57 1
        $em = $this->getDoctrine()->getManager();
58 1
        $article = $em->getRepository("AppBundle:Article")
59 1
            ->getArticleWithDep($slug);
60
61
        return [
62 1
            'article' => $article,
63 1
        ];
64
    }
65
66
    //ToDo: fix page over limit
67
    //ToDo: fix error 500 when sorting with undefined params and page 0
68
    /**
69
     * @param $sortBy
70
     * @param $param
71
     * @param $page
72
     * @Method("GET")
73
     * @Route("/{sortBy}/{param}/{pager}/{page}", name="sortArticles",
74
     *     defaults={"pager": "page", "page": 1},
75
     *     requirements={
76
     *          "sortBy": "category|tag|author|date",
77
     *          "pager": "page",
78
     *          "page": "[1-9]\d*",
79
     *     })
80
     * @Template("AppBundle:blog:blogPosts.html.twig")
81
     *
82
     * @return Response
83
     */
84 3
    public function sortAction($sortBy, $param, $page = 1)
85
    {
86 3
        if ($sortBy == 'date') {
87
            $dateConstraint = new Assert\Date();
88
            $dateConstraint->message = 'Invalid date';
89
90
            $errorList = $this->get('validator')->validate($param, $dateConstraint);
91
92
            if (0 !== count($errorList)) {
93
                throw $this->createNotFoundException(
94
                    $errorMessage = $errorList[0]->getMessage()
95
                );
96
            }
97
        }
98
99 3
        $em = $this->getDoctrine()->getManager();
100 3
        $articles = $em->getRepository("AppBundle:Article")
101 3
            ->getArticlesSorted($sortBy, $param, $page);
102
103
        return [
104 3
            'articles' => $articles,
105 3
        ];
106
    }
107
108
    /**
109
     * @param Request $request
110
     * @param $slug
111
     * @Route("/newCommentFor/{slug}", name="commentForm")
112
     * @Template("AppBundle:blog:commentForm.html.twig")
113
     *
114
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
115
     */
116 2
    public function newCommentAction(Request $request, $slug)
117
    {
118 2
        $em = $this->getDoctrine()->getManager();
119 2
        $article = $em->getRepository("AppBundle:Article")
0 ignored issues
show
Bug introduced by
The method findOneBySlug() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findOneBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
120 2
            ->findOneBySlug($slug);
121 2
        $comment = new Comment();
122 2
        $comment->setArticle($article);
123
124 2
        $form = $this->createForm(CommentType::class, $comment, [
125 2
            'em' => $em,
126 2
            'action' => $this->generateUrl('commentForm', ['slug' => $slug]),
127 2
            'method' => Request::METHOD_POST,
128 2
        ]);
129
130
        //ToDo: fix check isUserAnonymous
131 2
        if ($user = 'anonymous') {
0 ignored issues
show
Unused Code introduced by
$user is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
132
            $form
133 2
                ->add('user', EntityType::class, array(
134 2
                    'class' => 'AppBundle:User',
135 2
                    'choice_label' => 'name',
136 2
                    'placeholder' => '* Choose user (remove after security)',
137 2
                ))
138 2
                ->add('name', TextType::class, array(
139 2
                        'attr' => array('placeholder' => '* Name (anonymous)')
140 2
                    )
141 2
                )
142 2
                ->add('email', EmailType::class, array(
143 2
                        'attr' => array('placeholder' => '* Email (anonymous)')
144 2
                    )
145 2
                );
146 2
        }
147
148
        $form
149 2
            ->add('save', SubmitType::class, array(
150 2
                'label' => 'Submit Comment',
151 2
                'attr' => array('class' => "btn btn-primary")
152 2
            ));
153
154 2
        if ($request->getMethod() == 'POST') {
155
            $form->handleRequest($request);
156
            if ($form->isValid()) {
157
                $em->persist($comment);
158
                $em->flush();
159
160
//                return $this->redirectToRoute('showArticle', ['slug' => $slug]);
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
161
                return $this->redirectToRoute('success');
162
            }
163
        }
164
165
        return [
166 2
            'form' => $form->createView(),
167 2
        ];
168
    }
169
170
    /**
171
     * @param $slug
172
     * @param $page
173
     * @Route("/comments/{slug}/{pager}/{page}", name="articleComments",
174
     *     defaults={"pager": "page", "page": 1},
175
     *     requirements={
176
     *          "pager": "page",
177
     *          "page": "[1-9]\d*",
178
     *     })
179
     * @Template("AppBundle:blog:comments.html.twig")
180
     *
181
     * @return Response
182
     */
183 2
    public function showArticleCommentsAction($slug, $page = 1)
184
    {
185 2
        $em = $this->getDoctrine()->getManager();
186 2
        $comments = $em->getRepository("AppBundle:Comment")
187 2
            ->getArticleComment($slug, $page, 5);
188
189
        return [
190 2
            'comments' => $comments,
191 2
        ];
192
    }
193
194
    /**
195
     * @Route("/success", name="success")
196
     * @Template("AppBundle:blog:success.html.twig")
197
     *
198
     * @return Response
199
     */
200 1
    public function successAction()
201
    {
202 1
        return [];
203
    }
204
}
205