Completed
Push — master ( e428dc...30fa97 )
by Paweł
13s
created

ArticleController   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 172
Duplicated Lines 21.51 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 84.85%

Importance

Changes 0
Metric Value
wmc 15
lcom 1
cbo 10
dl 37
loc 172
ccs 28
cts 33
cp 0.8485
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
C listAction() 0 31 8
A getAction() 10 10 2
A updateAction() 19 19 2
A deleteAction() 0 8 1
A findOr404() 8 8 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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 Nelmio\ApiDocBundle\Annotation\ApiDoc;
18
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
19
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
20
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
21
use SWP\Component\Common\Criteria\Criteria;
22
use SWP\Component\Common\Pagination\PaginationData;
23
use SWP\Component\Common\Response\ResourcesListResponse;
24
use SWP\Component\Common\Response\ResponseContext;
25
use SWP\Component\Common\Response\SingleResourceResponse;
26
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
27
use Symfony\Component\HttpFoundation\Request;
28
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
29
use SWP\Bundle\ContentBundle\Form\Type\ArticleType;
30
31
class ArticleController extends Controller
32
{
33
    /**
34
     * List all articles for current tenant.
35
     *
36
     * @ApiDoc(
37
     *     resource=true,
38
     *     description="List all articles for current tenant",
39
     *     statusCodes={
40
     *         200="Returned on success.",
41
     *     },
42
     *     filters={
43
     *         {"name"="status", "dataType"="string", "pattern"="new|published|unpublished|canceled"},
44
     *         {"name"="route", "dataType"="integer"},
45
     *         {"name"="includeSubRoutes", "dataType"="boolean"},
46
     *         {"name"="publishedBefore", "dataType"="datetime", "pattern"="Y-m-d h:i:s"},
47
     *         {"name"="publishedAfter", "dataType"="datetime", "pattern"="Y-m-d h:i:s"},
48
     *         {"name"="author", "dataType"="string", "pattern"="John Doe | John Doe, Matt Smith"},
49
     *         {"name"="query", "dataType"="string", "pattern"="Part of title"}
50
     *     }
51
     * )
52
     * @Route("/api/{version}/content/articles/", options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_content_list_articles")
53
     * @Method("GET")
54
     *
55
     * @Cache(expires="10 minutes", public=true)
56
     *
57
     * @param Request $request
58
     *
59
     * @return ResourcesListResponse
60
     */
61
    public function listAction(Request $request)
62
    {
63
        $authors = '';
64
        if (null !== $request->query->get('author', null)) {
65
            $authors = explode(', ', $request->query->get('author'));
66
        }
67
68
        if ($request->query->get('route', false) && $request->query->get('includeSubRoutes', false)) {
69
            $routeObject = $this->get('swp.provider.route')->getOneById($request->query->get('route'));
70
71
            if (null !== $routeObject) {
72
                $ids = [$routeObject->getId()];
73
                foreach ($routeObject->getChildren() as $child) {
74
                    $ids[] = $child->getId();
75
                }
76 11
                $request->query->set('route', $ids);
77
            }
78 11
        }
79
80 11
        $articles = $this->get('swp.repository.article')
81
            ->getPaginatedByCriteria(new Criteria([
82
                'status' => $request->query->get('status', ''),
83
                'route' => $request->query->get('route', ''),
84 11
                'publishedBefore' => $request->query->has('publishedBefore') ? new \DateTime($request->query->get('publishedBefore')) : '',
85
                'publishedAfter' => $request->query->has('publishedAfter') ? new \DateTime($request->query->get('publishedAfter')) : '',
86
                'author' => $authors,
87
                'query' => $request->query->get('query', ''),
88
            ]), [], new PaginationData($request));
89
90
        return new ResourcesListResponse($articles);
91
    }
92
93
    /**
94
     * Show single tenant article.
95
     *
96
     * @ApiDoc(
97
     *     resource=true,
98
     *     description="Show single tenant article",
99
     *     statusCodes={
100
     *         200="Returned on success."
101
     *     }
102
     * )
103
     * @Route("/api/{version}/content/articles/{id}", options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_content_show_articles", requirements={"id"=".+"})
104
     * @Method("GET")
105
     *
106
     * @Cache(expires="10 minutes", public=true)
107
     */
108 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...
109
    {
110
        $article = $this->get('swp.provider.article')->getOneById($id);
111
112
        if (null === $article) {
113
            throw new NotFoundHttpException('Article was not found.');
114 4
        }
115
116 4
        return new SingleResourceResponse($article);
117 4
    }
118 4
119
    /**
120 4
     * Updates articles.
121
     *
122 4
     * Possible article statuses are:
123 4
     *
124 4
     *  * new
125 4
     *  * published
126 4
     *  * unpublished
127 4
     *  * canceled
128
     *
129 4
     * Changing status from any status to `published` will make article visible for every user.
130
     *
131
     * Changing status from `published` to any other will make article hidden for user who don't have rights to see unpublished articles.
132
     *
133
     * @ApiDoc(
134
     *     resource=true,
135 4
     *     description="Updates articles",
136
     *     statusCodes={
137 4
     *         200="Returned on success.",
138 4
     *         400="Returned when validation failed.",
139 4
     *         500="Returned when unexpected error."
140
     *     },
141
     *     input="SWP\Bundle\ContentBundle\Form\Type\ArticleType"
142 1
     * )
143
     * @Route("/api/{version}/content/articles/{id}", options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_content_update_articles", requirements={"id"=".+"})
144 1
     * @Method("PATCH")
145 1
     */
146 1 View Code Duplication
    public function updateAction(Request $request, $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...
147
    {
148
        $objectManager = $this->get('swp.object_manager.article');
149
        $article = $this->findOr404($id);
150
        $originalArticleStatus = $article->getStatus();
151 1
152
        $form = $this->createForm(ArticleType::class, $article, ['method' => $request->getMethod()]);
153 4
154
        $form->handleRequest($request);
155 4
        if ($form->isValid()) {
156
            $this->get('swp.service.article')->reactOnStatusChange($originalArticleStatus, $article);
157
            $objectManager->flush();
158
            $objectManager->refresh($article);
159 4
160
            return new SingleResourceResponse($article);
161
        }
162
163
        return new SingleResourceResponse($form, new ResponseContext(500));
164
    }
165
166
    /**
167
     * Delete Article.
168
     *
169
     * @ApiDoc(
170
     *     resource=true,
171
     *     description="Deletes articles",
172
     *     statusCodes={
173
     *         204="Returned on success.",
174
     *         404="Returned when article not found.",
175
     *         500="Returned when unexpected error."
176
     *     }
177
     * )
178
     * @Route("/api/{version}/content/articles/{id}", options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_content_delete_articles", requirements={"id"=".+"})
179
     * @Method("DELETE")
180
     *
181
     * @param int $id
182
     *
183
     * @return SingleResourceResponse
184
     */
185
    public function deleteAction($id)
186
    {
187
        $objectManager = $this->get('swp.object_manager.article');
188
        $objectManager->remove($this->findOr404($id));
189
        $objectManager->flush();
190
191
        return new SingleResourceResponse(null, new ResponseContext(204));
192
    }
193
194 View Code Duplication
    private function findOr404($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...
195
    {
196
        if (null === $article = $this->get('swp.provider.article')->getOneById($id)) {
197
            throw new NotFoundHttpException('Article was not found.');
198
        }
199
200
        return $article;
201
    }
202
}
203