Completed
Push — 3.x-dev-kit ( 21be5a )
by
unknown
03:10
created

PostController::viewAction()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 2 Features 0
Metric Value
c 5
b 2
f 0
dl 0
loc 27
rs 8.5806
cc 4
eloc 18
nc 3
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[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 Sonata\NewsBundle\Controller;
13
14
use Sonata\NewsBundle\Model\BlogInterface;
15
use Sonata\NewsBundle\Model\CommentInterface;
16
use Sonata\NewsBundle\Model\CommentManagerInterface;
17
use Sonata\NewsBundle\Model\PostInterface;
18
use Sonata\NewsBundle\Model\PostManagerInterface;
19
use Sonata\SeoBundle\Seo\SeoPageInterface;
20
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
21
use Symfony\Component\Form\FormInterface;
22
use Symfony\Component\HttpFoundation\RedirectResponse;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpFoundation\Response;
25
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
26
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
27
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
28
29
class PostController extends Controller
30
{
31
    /**
32
     * @return RedirectResponse
33
     */
34
    public function homeAction()
35
    {
36
        return $this->redirect($this->generateUrl('sonata_news_archive'));
37
    }
38
39
    /**
40
     * @param array   $criteria
41
     * @param array   $parameters
42
     * @param Request $request
43
     *
44
     * @return Response
45
     */
46
    public function renderArchive(array $criteria = array(), array $parameters = array(), Request $request = null)
47
    {
48
        $request = $this->resolveRequest($request);
49
50
        $pager = $this->getPostManager()->getPager(
51
            $criteria,
52
            $request->get('page', 1)
53
        );
54
55
        $parameters = array_merge(array(
56
            'pager' => $pager,
57
            'blog' => $this->getBlog(),
58
            'tag' => false,
59
            'collection' => false,
60
            'route' => $request->get('_route'),
61
            'route_parameters' => $request->get('_route_params'),
62
        ), $parameters);
63
64
        $response = $this->render(sprintf('SonataNewsBundle:Post:archive.%s.twig', $request->getRequestFormat()), $parameters);
65
66
        if ('rss' === $request->getRequestFormat()) {
67
            $response->headers->set('Content-Type', 'application/rss+xml');
68
        }
69
70
        return $response;
71
    }
72
73
    /**
74
     * @param Request $request
75
     *
76
     * @return Response
77
     */
78
    public function archiveAction(Request $request = null)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
79
    {
80
        return $this->renderArchive();
81
    }
82
83
    /**
84
     * @param string  $tag
85
     * @param Request $request
86
     *
87
     * @return Response
88
     *
89
     * @throws NotFoundHttpException
90
     */
91
    public function tagAction($tag, Request $request = null)
92
    {
93
        $request = $this->resolveRequest($request);
94
95
        $tag = $this->get('sonata.classification.manager.tag')->findOneBy(array(
96
            'slug' => $tag,
97
            'enabled' => true,
98
        ));
99
100
        if (!$tag || !$tag->getEnabled()) {
101
            throw new NotFoundHttpException('Unable to find the tag');
102
        }
103
104
        return $this->renderArchive(array('tag' => $tag->getSlug()), array('tag' => $tag), $request);
105
    }
106
107
    /**
108
     * @param $collection
109
     * @param Request $request
110
     *
111
     * @return Response
112
     *
113
     * @throws NotFoundHttpException
114
     */
115
    public function collectionAction($collection, Request $request = null)
116
    {
117
        $request = $this->resolveRequest($request);
118
119
        $collection = $this->get('sonata.classification.manager.collection')->findOneBy(array(
120
            'slug' => $collection,
121
            'enabled' => true,
122
        ));
123
124
        if (!$collection || !$collection->getEnabled()) {
125
            throw new NotFoundHttpException('Unable to find the collection');
126
        }
127
128
        return $this->renderArchive(array('collection' => $collection), array('collection' => $collection), $request);
129
    }
130
131
    /**
132
     * @param string  $year
133
     * @param string  $month
134
     * @param Request $request
135
     *
136
     * @return Response
137
     */
138
    public function archiveMonthlyAction($year, $month, Request $request = null)
139
    {
140
        $request = $this->resolveRequest($request);
141
142
        return $this->renderArchive(array(
143
            'date' => $this->getPostManager()->getPublicationDateQueryParts(sprintf('%d-%d-%d', $year, $month, 1), 'month'),
144
        ), array(), $request);
145
    }
146
147
    /**
148
     * @param string  $year
149
     * @param Request $request
150
     *
151
     * @return Response
152
     */
153
    public function archiveYearlyAction($year, Request $request = null)
154
    {
155
        $request = $this->resolveRequest($request);
156
157
        return $this->renderArchive(array(
158
            'date' => $this->getPostManager()->getPublicationDateQueryParts(sprintf('%d-%d-%d', $year, 1, 1), 'year'),
159
        ), array(), $request);
160
    }
161
162
    /**
163
     * @throws NotFoundHttpException
164
     *
165
     * @param $permalink
166
     *
167
     * @return Response
168
     */
169
    public function viewAction($permalink)
170
    {
171
        $post = $this->getPostManager()->findOneByPermalink($permalink, $this->getBlog());
0 ignored issues
show
Bug introduced by
The method findOneByPermalink() does not exist on Sonata\NewsBundle\Model\PostManagerInterface. 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...
172
173
        if (!$post || !$post->isPublic()) {
174
            throw new NotFoundHttpException('Unable to find the post');
175
        }
176
177
        if ($seoPage = $this->getSeoPage()) {
178
            $seoPage
179
                ->setTitle($post->getTitle())
180
                ->addMeta('name', 'description', $post->getAbstract())
181
                ->addMeta('property', 'og:title', $post->getTitle())
182
                ->addMeta('property', 'og:type', 'blog')
183
                ->addMeta('property', 'og:url', $this->generateUrl('sonata_news_view', array(
184
                    'permalink' => $this->getBlog()->getPermalinkGenerator()->generate($post, true),
0 ignored issues
show
Unused Code introduced by
The call to PermalinkInterface::generate() has too many arguments starting with true.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
185
                ), UrlGeneratorInterface::ABSOLUTE_URL))
186
                ->addMeta('property', 'og:description', $post->getAbstract())
187
            ;
188
        }
189
190
        return $this->render('SonataNewsBundle:Post:view.html.twig', array(
191
            'post' => $post,
192
            'form' => false,
193
            'blog' => $this->getBlog(),
194
        ));
195
    }
196
197
    /**
198
     * @return SeoPageInterface
199
     */
200
    public function getSeoPage()
201
    {
202
        if ($this->has('sonata.seo.page')) {
203
            return $this->get('sonata.seo.page');
204
        }
205
206
        return;
207
    }
208
209
    /**
210
     * @param int $postId
211
     *
212
     * @return Response
213
     */
214
    public function commentsAction($postId)
215
    {
216
        $pager = $this->getCommentManager()
217
            ->getPager(array(
218
                'postId' => $postId,
219
                'status' => CommentInterface::STATUS_VALID,
220
            ), 1, 500); //no limit
221
222
        return $this->render('SonataNewsBundle:Post:comments.html.twig', array(
223
            'pager' => $pager,
224
        ));
225
    }
226
227
    /**
228
     * @param $postId
229
     * @param bool $form
230
     *
231
     * @return Response
232
     */
233
    public function addCommentFormAction($postId, $form = false)
234
    {
235
        if (!$form) {
236
            $post = $this->getPostManager()->findOneBy(array(
237
                'id' => $postId,
238
            ));
239
240
            $form = $this->getCommentForm($post);
0 ignored issues
show
Documentation introduced by
$post is of type object|null, but the function expects a object<Sonata\NewsBundle\Model\PostInterface>.

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...
241
        }
242
243
        return $this->render('SonataNewsBundle:Post:comment_form.html.twig', array(
244
            'form' => $form->createView(),
0 ignored issues
show
Bug introduced by
It seems like $form is not always an object, but can also be of type boolean. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
245
            'post_id' => $postId,
246
        ));
247
    }
248
249
    /**
250
     * @param $post
251
     *
252
     * @return FormInterface
253
     */
254
    public function getCommentForm(PostInterface $post)
255
    {
256
        $comment = $this->getCommentManager()->create();
257
        $comment->setPost($post);
258
        $comment->setStatus($post->getCommentsDefaultStatus());
259
260
        return $this->get('form.factory')->createNamed('comment', 'sonata_post_comment', $comment);
261
    }
262
263
    /**
264
     * @throws NotFoundHttpException
265
     *
266
     * @param string  $id
267
     * @param Request $request
268
     *
269
     * @return Response
270
     */
271
    public function addCommentAction($id, Request $request = null)
272
    {
273
        $request = $this->resolveRequest($request);
274
275
        $post = $this->getPostManager()->findOneBy(array(
276
            'id' => $id,
277
        ));
278
279
        if (!$post) {
280
            throw new NotFoundHttpException(sprintf('Post (%d) not found', $id));
281
        }
282
283
        if (!$post->isCommentable()) {
284
            // todo add notice
285
            return new RedirectResponse($this->generateUrl('sonata_news_view', array(
286
                'permalink' => $this->getBlog()->getPermalinkGenerator()->generate($post),
287
            )));
288
        }
289
290
        $form = $this->getCommentForm($post);
291
        $form->submit($request);
292
293
        if ($form->isValid()) {
294
            $comment = $form->getData();
295
296
            $this->getCommentManager()->save($comment);
297
            $this->get('sonata.news.mailer')->sendCommentNotification($comment);
298
299
            // todo : add notice
300
            return new RedirectResponse($this->generateUrl('sonata_news_view', array(
301
                'permalink' => $this->getBlog()->getPermalinkGenerator()->generate($post),
302
            )));
303
        }
304
305
        return $this->render('SonataNewsBundle:Post:view.html.twig', array(
306
            'post' => $post,
307
            'form' => $form,
308
        ));
309
    }
310
311
    /**
312
     * @param string $commentId
313
     * @param string $hash
314
     * @param string $status
315
     *
316
     * @return RedirectResponse
317
     *
318
     * @throws AccessDeniedException
319
     */
320
    public function commentModerationAction($commentId, $hash, $status)
321
    {
322
        $comment = $this->getCommentManager()->findOneBy(array('id' => $commentId));
323
324
        if (!$comment) {
325
            throw new AccessDeniedException();
326
        }
327
328
        $computedHash = $this->get('sonata.news.hash.generator')->generate($comment);
329
330
        if ($computedHash != $hash) {
331
            throw new AccessDeniedException();
332
        }
333
334
        $comment->setStatus($status);
335
336
        $this->getCommentManager()->save($comment);
337
338
        return new RedirectResponse($this->generateUrl('sonata_news_view', array(
339
            'permalink' => $this->getBlog()->getPermalinkGenerator()->generate($comment->getPost()),
340
        )));
341
    }
342
343
    /**
344
     * @return PostManagerInterface
345
     */
346
    protected function getPostManager()
347
    {
348
        return $this->get('sonata.news.manager.post');
349
    }
350
351
    /**
352
     * @return CommentManagerInterface
353
     */
354
    protected function getCommentManager()
355
    {
356
        return $this->get('sonata.news.manager.comment');
357
    }
358
359
    /**
360
     * @return BlogInterface
361
     */
362
    protected function getBlog()
363
    {
364
        return $this->get('sonata.news.blog');
365
    }
366
367
    /**
368
     * To keep backwards compatibility with older Sonata News code.
369
     *
370
     * @internal
371
     *
372
     * @param Request $request
373
     *
374
     * @return Request
375
     */
376
    private function resolveRequest(Request $request = null)
377
    {
378
        if (null === $request) {
379
            return $this->getRequest();
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated with message: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
380
        }
381
382
        return $request;
383
    }
384
}
385