Completed
Push — master ( 3d485f...407dff )
by Paweł
66:49
created

ContainerController::getNotConvertedLinks()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 15

Duplication

Lines 4
Ratio 17.39 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 4
loc 23
ccs 0
cts 0
cp 0
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 15
nc 4
nop 1
crap 20
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 SWP\Component\Common\Criteria\Criteria;
18
use SWP\Component\Common\Pagination\PaginationData;
19
use SWP\Component\TemplatesSystem\Gimme\Model\ContainerInterface;
20
use SWP\Component\TemplatesSystem\Gimme\Model\WidgetModelInterface;
21
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
22
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
23
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
24
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
25
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
26
use SWP\Component\Common\Response\ResourcesListResponse;
27
use SWP\Component\Common\Response\ResponseContext;
28
use SWP\Component\Common\Response\SingleResourceResponse;
29
use SWP\Bundle\TemplatesSystemBundle\Form\Type\ContainerType;
30
use Symfony\Component\HttpFoundation\Request;
31
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
32
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
33
34
class ContainerController extends Controller
35
{
36
    /**
37
     * Lists all registered containers.
38
     *
39
     * @ApiDoc(
40
     *     resource=true,
41
     *     description="Lists all registered containers",
42
     *     statusCodes={
43
     *         200="Returned on success."
44
     *     }
45
     * )
46
     * @Route("/api/{version}/templates/containers/", options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_templates_list_containers")
47
     * @Method("GET")
48
     * @Cache(expires="10 minutes", public=true)
49
     *
50 1
     * @param Request $request
51
     *
52 1
     * @return ResourcesListResponse
53 1
     */
54 1
    public function listAction(Request $request)
55 1
    {
56 1
        $repository = $this->get('swp.repository.container');
57 1
        $containers = $repository->getPaginatedByCriteria(new Criteria(), [], new PaginationData($request));
58
59
        return new ResourcesListResponse($containers);
60 1
    }
61
62
    /**
63
     * Get single container.
64 1
     *
65
     * @ApiDoc(
66
     *     resource=true,
67
     *     description="Get single container",
68
     *     statusCodes={
69
     *         200="Returned on success.",
70
     *         404="Container not found"
71
     *     }
72
     * )
73
     * @Route("/api/{version}/templates/containers/{uuid}", requirements={"uuid"="\w+"}, options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_templates_get_container")
74
     * @Method("GET")
75
     * @Cache(expires="10 minutes", public=true)
76
     *
77
     * @param string $uuid
78
     *
79
     * @return SingleResourceResponse
80
     */
81
    public function getAction($uuid)
82
    {
83 1
        $container = $this->get('swp.provider.container')->getOneById($uuid);
84
        if (!$container) {
85 1
            throw new NotFoundHttpException('Container with this uuid was not found.');
86 1
        }
87 1
88 1
        return new SingleResourceResponse($container);
89
    }
90 1
91
    /**
92
     * Render single container and it's widgets.
93
     *
94 1
     * @ApiDoc(
95
     *     resource=true,
96
     *     description="Render single container and it's widgets.",
97
     *     statusCodes={
98
     *         200="Returned on success.",
99
     *         404="Container not found"
100
     *     }
101
     * )
102
     * @Route("/api/{version}/templates/containers/{uuid}/render", requirements={"uuid"="\w+"}, options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_templates_render_container")
103
     * @Method("GET")
104
     * @Cache(expires="10 minutes", public=true)
105
     */
106
    public function renderAction($uuid)
107
    {
108
        /** @var ContainerInterface $container */
109
        $container = $this->get('swp.provider.container')->getOneById($uuid);
110
111
        if (!$container) {
112
            throw new NotFoundHttpException('Container with this uuid was not found.');
113 3
        }
114
115 3
        $content = $this->get('templating')
116 3
            ->render('SWPCoreBundle:Container:render.html.twig', ['containerName' => $container->getName()]);
117 3
118 3
        return new SingleResourceResponse(['content' => $content]);
119
    }
120 3
121
    /**
122
     * Update single container.
123
     *
124 3
     * @ApiDoc(
125 3
     *     resource=true,
126
     *     description="Update single container",
127
     *     statusCodes={
128 3
     *         201="Returned on success.",
129 3
     *         404="Container not found",
130 3
     *         422="Container id is not number"
131 3
     *     },
132
     *     input="SWP\Bundle\TemplatesSystemBundle\Form\Type\ContainerType"
133 1
     * )
134 1
     * @Route("/api/{version}/templates/containers/{uuid}", requirements={"uuid"="\w+"}, options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_templates_update_container")
135
     * @Method("PATCH")
136
     *
137
     * @param Request $request
138 1
     * @param string  $uuid
139 1
     *
140 1
     * @throws NotFoundHttpException
141 1
     * @throws UnprocessableEntityHttpException
142 1
     *
143
     * @return SingleResourceResponse
144
     */
145 View Code Duplication
    public function updateAction(Request $request, $uuid)
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...
146 3
    {
147 3
        $container = $this->getContainerForUpdate($uuid);
148
        if (!$container) {
149 3
            throw new NotFoundHttpException('Container with this uuid was not found.');
150
        }
151
152
        $form = $this->createForm(ContainerType::class, $container, [
153
            'method' => $request->getMethod(),
154
        ]);
155
156
        $form->handleRequest($request);
157
        if ($form->isValid()) {
158
            $container = $this->get('swp_template_engine.container.service')
159
                ->updateContainer($container, $form->get('data')->getExtraData());
160
161
            return new SingleResourceResponse($container, new ResponseContext(201));
162
        }
163
164
        return new SingleResourceResponse($form);
165
    }
166
167
    /**
168
     * Link or Unlink resource with Container.
169
     *
170
     * **link or unlink widget**:
171
     *
172
     *     header name: "link"
173
     *     header value: "</api/{version}/templates/widgets/{id}; rel="widget">"
174
     *
175
     * or with specific position:
176
     *
177
     *     header name: "link"
178
     *     header value: "</api/{version}/templates/widgets/{id}; rel="widget">,<1; rel="widget-position">"
179
     *
180
     * @ApiDoc(
181
     *     statusCodes={
182
     *         201="Returned when successful",
183
     *         404="Returned when resource not found",
184
     *         409={
185
     *           "Returned when the link already exists",
186
     *         }
187
     *     }
188
     * )
189
     *
190 2
     * @Route("/api/{version}/templates/containers/{uuid}", requirements={"uuid"="\w+"}, defaults={"version"="v1"}, name="swp_api_templates_link_container")
191
     *
192 2
     * @Method("LINK|UNLINK")
193
     *
194
     * @param Request $request
195
     * @param string  $uuid
196 2
     *
197 2
     * @throws NotFoundHttpException
198 2
     * @throws \Exception
199 2
     *
200
     * @return SingleResourceResponse
201 2
     */
202
    public function linkUnlinkToContainerAction(Request $request, $uuid)
203
    {
204
        $entityManager = $this->get('swp.object_manager.container');
205 2
        $container = $this->getContainerForUpdate($uuid);
206 2
        if (!$container) {
207 2
            throw new NotFoundHttpException('Container with this uuid was not found.');
208
        }
209
210
        $matched = false;
211 2
        foreach ($request->attributes->get('links', []) as $key => $objectArray) {
212 2
            if (!is_array($objectArray)) {
213
                continue;
214
            }
215
216 2
            $object = $objectArray['object'];
217 2
            if ($object instanceof \Exception) {
218 2
                throw $object;
219 2
            }
220 2
221
            if ($object instanceof WidgetModelInterface) {
222 2
                $container = $this->get('swp_template_engine.container.service')
223 2
                    ->linkUnlinkWidget($object, $container, $request);
224 2
                $matched = true;
225 1
                break;
226 1
            }
227 1
        }
228
        if ($matched === false) {
229
            throw new NotFoundHttpException('Any supported link object was not found');
230
        }
231
232 2
        $entityManager->flush();
233
234
        return new SingleResourceResponse($container, new ResponseContext(201));
235
    }
236 2
237 2
    private function getContainerForUpdate($uuid)
238 2
    {
239
        $revisionContext = $this->get('swp_revision.context.revision');
240
        $currentRenditionBackup = $revisionContext->getCurrentRevision();
241 2
        $revisionContext->setCurrentRevision($revisionContext->getWorkingRevision());
242 1
243 1
        $container = $this->get('swp.provider.container')->getOneById($uuid);
244 1
245 2
        $revisionContext->setCurrentRevision($currentRenditionBackup);
246
        if (null === $container) {
247 1
            if ($revisionContext->getCurrentRevision() !== $revisionContext->getPublishedRevision()) {
248 1
                $revisionContext->setCurrentRevision($revisionContext->getPublishedRevision());
249
            }
250
            $container = $this->get('swp.provider.container')->getOneById($uuid);
251 1
            $revisionContext->setCurrentRevision($currentRenditionBackup);
252
        }
253
254 2
        return $container;
255 2
    }
256
}
257