Completed
Push — master ( bb050e...36e41a )
by Paweł
11:10
created

ArticleController   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 171
Duplicated Lines 10.53 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 84.85%

Importance

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

5 Methods

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