Completed
Push — master ( 6469d9...c2139f )
by Paweł
61:46
created

WidgetController::updateAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 16
Ratio 100 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 16
loc 16
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 2
crap 2
1
<?php
2
3
/*
4
 * This file is part of the Superdesk Web Publisher Core 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\CoreBundle\Controller;
16
17
use FOS\RestBundle\Controller\FOSRestController;
18
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
19
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
20
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
21
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
22
use SWP\Component\Common\Criteria\Criteria;
23
use SWP\Component\Common\Pagination\PaginationData;
24
use SWP\Component\Common\Response\ResourcesListResponse;
25
use SWP\Component\Common\Response\ResponseContext;
26
use SWP\Component\Common\Response\SingleResourceResponse;
27
use SWP\Bundle\TemplatesSystemBundle\Form\Type\WidgetType;
28
use SWP\Bundle\CoreBundle\Model\WidgetModel;
29
use Symfony\Component\HttpFoundation\Request;
30
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
31
32
class WidgetController extends FOSRestController
33
{
34
    /**
35
     * Lists all registered widgets.
36
     *
37
     * @ApiDoc(
38
     *     resource=true,
39
     *     description="Lists all registered widgets",
40
     *     statusCodes={
41
     *         200="Returned on success."
42
     *     }
43
     * )
44
     * @Route("/api/{version}/templates/widgets/", options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_templates_list_widgets")
45
     * @Method("GET")
46
     * @Cache(expires="10 minutes", public=true)
47
     */
48 2
    public function listAction(Request $request)
49
    {
50 2
        $repository = $this->get('swp.repository.widget_model');
51 2
52 2
        $widgets = $repository->getPaginatedByCriteria(new Criteria(), [], new PaginationData($request));
53 2
54 2
        return new ResourcesListResponse($widgets);
55 2
    }
56
57
    /**
58 2
     * Get single widget.
59
     *
60
     * @ApiDoc(
61
     *     resource=true,
62 2
     *     description="Get single widget",
63
     *     statusCodes={
64
     *         200="Returned on success.",
65
     *         404="Widget not found",
66
     *         422="Widget id is not number"
67
     *     }
68
     * )
69
     * @Route("/api/{version}/templates/widgets/{id}", requirements={"id"="\d+"}, options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_templates_get_widget")
70
     * @Method("GET")
71
     */
72
    public function getAction($id)
73
    {
74
        return new SingleResourceResponse($this->findOr404($id));
75
    }
76
77
    /**
78
     * Create new widget.
79
     *
80 3
     * Note:
81
     *
82 3
     *     Widget Type can be widget ID or his class (string).
83
     *     Example: "SWP\\Bundle\\CoreBundle\\Widget\\ContentListWidget"
84
     *
85
     * @ApiDoc(
86 3
     *     resource=true,
87 3
     *     description="Create new widget",
88
     *     statusCodes={
89 3
     *         201="Returned on success.",
90
     *         400="Returned when form have errors"
91
     *     },
92
     *     input="SWP\Bundle\TemplatesSystemBundle\Form\Type\WidgetType"
93
     * )
94 3
     * @Route("/api/{version}/templates/widgets/", options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_templates_create_widget")
95 2
     * @Method("POST")
96
     */
97 View Code Duplication
    public function createAction(Request $request)
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...
98 1
    {
99
        $widget = new WidgetModel();
100
        $form = $this->createForm(WidgetType::class, $widget);
101
        $form->handleRequest($request);
102
        if ($form->isValid()) {
103
            $this->ensureWidgetExists($widget->getName());
104
            $this->getWidgetRepository()->add($widget);
105
106
            return new SingleResourceResponse($widget, new ResponseContext(201));
107
        }
108
109
        return new SingleResourceResponse($form, new ResponseContext(400));
110
    }
111
112
    /**
113
     * Delete single widget.
114
     *
115
     * @ApiDoc(
116 2
     *     resource=true,
117
     *     description="Delete single widget",
118 2
     *     statusCodes={
119
     *         204="Returned on success.",
120 2
     *         404="Widget not found",
121 2
     *         422="Widget id is not number"
122 2
     *     }
123 2
     * )
124 2
     * @Route("/api/{version}/templates/widgets/{id}", requirements={"id"="\d+"}, options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_templates_delete_widget")
125 2
     * @Method("DELETE")
126
     */
127 2
    public function deleteAction($id)
128
    {
129
        $entityManager = $this->get('doctrine')->getManager();
130
        $widget = $this->findOr404($id);
131
132
        foreach ($widget->getContainers() as $containerWidget) {
133
            $entityManager->remove($containerWidget);
134
        }
135
136
        $this->getWidgetRepository()->remove($widget);
137
138
        return new SingleResourceResponse(null, new ResponseContext(204));
139
    }
140
141
    /**
142
     * Update single widget.
143
     *
144
     * @ApiDoc(
145
     *     resource=true,
146
     *     description="Update single widget",
147
     *     statusCodes={
148 1
     *         201="Returned on success.",
149
     *         404="Widget not found",
150 1
     *         422="Widget id is not number",
151
     *         405="Method Not Allowed"
152
     *     },
153
     *     input="SWP\Bundle\TemplatesSystemBundle\Form\Type\WidgetType"
154 1
     * )
155 1
     * @Route("/api/{version}/templates/widgets/{id}", requirements={"id"="\d+"}, options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_templates_update_widget")
156
     * @Method("PATCH")
157 1
     */
158 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...
159
    {
160
        $widget = $this->findOr404($id);
161 1
        $form = $this->createForm(WidgetType::class, $widget, [
162
            'method' => $request->getMethod(),
163
        ]);
164
165 1
        $form->handleRequest($request);
166 1
        if ($form->isValid()) {
167
            $this->getWidgetRepository()->add($widget);
168 1
169
            return new SingleResourceResponse($widget, new ResponseContext(201));
170
        }
171
172
        return new SingleResourceResponse($form);
173
    }
174
175
    private function findOr404(int $id)
176
    {
177
        if (null === $widget = $this->getWidgetRepository()->findOneById($id)) {
178
            throw $this->createNotFoundException(sprintf('Widget with id "%s" was not found.', $id));
179
        }
180
181
        return $widget;
182
    }
183
184
    private function ensureWidgetExists(string $name)
185
    {
186
        if (null !== $widget = $this->getWidgetRepository()->findOneByName($name)) {
187
            throw new ConflictHttpException(sprintf('Widget with name "%s" already exists.', $name));
188 1
        }
189
190 1
        return $widget;
191
    }
192
193
    private function getWidgetRepository()
194 1
    {
195 1
        return $this->get('swp.repository.widget_model');
196
    }
197
}
198