Completed
Push — master ( 586166...fecb59 )
by Paweł
47:58
created

ArticleController::updateAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 15
cts 15
cp 1
rs 9.0856
c 0
b 0
f 0
cc 2
eloc 15
nc 2
nop 2
crap 2
1
<?php
2
3
/**
4
 * This file is part of the Superdesk Web Publisher Content Bundle.
5
 *
6
 * Copyright 2015 Sourcefabric z.u. and contributors.
7
 *
8
 * For the full copyright and license information, please see the
9
 * AUTHORS and LICENSE files distributed with this source code.
10
 *
11
 * @copyright 2015 Sourcefabric z.ú
12
 * @license http://www.superdesk.org/license
13
 */
14
15
namespace SWP\Bundle\ContentBundle\Controller;
16
17
use FOS\RestBundle\Controller\FOSRestController;
18
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
19
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
20
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
21
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
22
use FOS\RestBundle\View\View;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
25
use SWP\Bundle\ContentBundle\Form\Type\ArticleType;
26
use SWP\Bundle\ContentBundle\Model\ArticleInterface;
27
use SWP\Component\Common\Event\HttpCacheEvent;
28
29
class ArticleController extends FOSRestController
30
{
31
    /**
32
     * List all articles for current tenant.
33
     *
34
     * @ApiDoc(
35
     *     resource=true,
36
     *     description="List all articles for current tenant",
37
     *     statusCodes={
38
     *         200="Returned on success.",
39
     *     }
40
     * )
41
     * @Route("/api/{version}/content/articles/", options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_content_list_articles")
42
     * @Method("GET")
43
     *
44
     * @Cache(expires="10 minutes", public=true)
45
     */
46
    public function listAction(Request $request)
47
    {
48
        $articles = $this->get('knp_paginator')->paginate(
49
            $this->get('swp.repository.article')->findAllArticles(),
50
            $request->get('page', 1),
51
            $request->get('limit', 10)
52
        );
53
54
        $view = View::create($this->get('swp_pagination_rep')->createRepresentation($articles, $request), 200);
55
56
        return $this->handleView($view);
57
    }
58
59
    /**
60
     * Show single tenant article.
61
     *
62
     * @ApiDoc(
63
     *     resource=true,
64
     *     description="Show single tenant article",
65
     *     statusCodes={
66
     *         200="Returned on success."
67
     *     }
68
     * )
69
     * @Route("/api/{version}/content/articles/{id}", options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_content_show_articles", requirements={"id"=".+"})
70
     * @Method("GET")
71
     *
72
     * @Cache(expires="10 minutes", public=true)
73
     */
74 6 View Code Duplication
    public function getAction($id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
75
    {
76 6
        $article = $this->get('swp.provider.article')->getOneById($id);
77
78 6
        if (null === $article) {
79
            throw new NotFoundHttpException('Article was not found.');
80
        }
81
82 6
        return $this->handleView(View::create($article, 200));
83
    }
84
85
    /**
86
     * Updates articles.
87
     *
88
     * Possible article statuses are:
89
     *
90
     *  * new
91
     *  * submitted
92
     *  * published
93
     *  * unpublished
94
     *
95
     * Changing status from any status to `published` will make article visible for every user.
96
     *
97
     * Changing status from `published` to any other will make article hidden for user who don't have rights to see unpublished articles.
98
     *
99
     * @ApiDoc(
100
     *     resource=true,
101
     *     description="Updates articles",
102
     *     statusCodes={
103
     *         200="Returned on success.",
104
     *         400="Returned when validation failed.",
105
     *         500="Returned when unexpected error."
106
     *     },
107
     *     input="SWP\Bundle\ContentBundle\Form\Type\ArticleType"
108
     * )
109
     * @Route("/api/{version}/content/articles/{id}", options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_content_update_articles", requirements={"id"=".+"})
110
     * @Method("PATCH")
111
     */
112 9
    public function updateAction(Request $request, $id)
113
    {
114 9
        $objectManager = $this->get('swp.object_manager.article');
115 9
        $article = $this->findOr404($id);
116 9
        $originalArticleStatus = $article->getStatus();
117
118 9
        $form = $this->createForm(ArticleType::class, $article, ['method' => $request->getMethod()]);
119
120 9
        $form->handleRequest($request);
121 9
        if ($form->isValid()) {
122 8
            $this->reactOnStatusChange($originalArticleStatus, $article);
123 8
            $article->setUpdatedAt(new \DateTime());
124 8
            $objectManager->flush();
125 8
            $objectManager->refresh($article);
126
127 8
            $this->get('event_dispatcher')
128 8
            ->dispatch(HttpCacheEvent::EVENT_NAME, new HttpCacheEvent($article));
129
130 8
            return $this->handleView(View::create($article, 200));
131
        }
132
133 1
        return $this->handleView(View::create($form, 500));
134
    }
135
136 8
    private function reactOnStatusChange($originalArticleStatus, ArticleInterface $article)
137
    {
138 8
        $newArticleStatus = $article->getStatus();
139 8
        if ($originalArticleStatus === $newArticleStatus) {
140 4
            return;
141
        }
142
143 4
        $articleService = $this->container->get('swp.service.article');
144
        switch ($newArticleStatus) {
145 4
            case ArticleInterface::STATUS_PUBLISHED:
146 4
                $articleService->publish($article);
147 4
                break;
148
            default:
149 1
                $articleService->unpublish($article, $newArticleStatus);
150 1
                break;
151
        }
152 4
    }
153
154 9
    private function findOr404($id)
155
    {
156 9
        if (null === $article = $this->get('swp.provider.article')->getOneById($id)) {
157
            throw new NotFoundHttpException('Article was not found.');
158
        }
159
160 9
        return $article;
161
    }
162
}
163