Completed
Pull Request — develop (#147)
by Wachter
14:07
created

ArticlePageController::handleActionParameter()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 8
rs 9.4285
c 1
b 0
f 0
cc 2
eloc 5
nc 2
nop 3
1
<?php
2
3
/*
4
 * This file is part of Sulu.
5
 *
6
 * (c) MASSIVE ART WebServices GmbH
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Sulu\Bundle\ArticleBundle\Controller;
13
14
use FOS\RestBundle\Controller\Annotations\Post;
15
use FOS\RestBundle\Routing\ClassResourceInterface;
16
use JMS\Serializer\SerializationContext;
17
use Sulu\Bundle\ArticleBundle\Admin\ArticleAdmin;
18
use Sulu\Bundle\ArticleBundle\Document\ArticlePageDocument;
19
use Sulu\Bundle\ArticleBundle\Document\Form\ArticlePageDocumentType;
20
use Sulu\Bundle\ArticleBundle\Exception\ArticlePageNotFoundException;
21
use Sulu\Bundle\ArticleBundle\Exception\ParameterNotAllowedException;
22
use Sulu\Component\Content\Form\Exception\InvalidFormException;
23
use Sulu\Component\Content\Mapper\ContentMapperInterface;
24
use Sulu\Component\DocumentManager\DocumentManagerInterface;
25
use Sulu\Component\Rest\Exception\MissingParameterException;
26
use Sulu\Component\Rest\Exception\RestException;
27
use Sulu\Component\Rest\RequestParametersTrait;
28
use Sulu\Component\Rest\RestController;
29
use Sulu\Component\Security\SecuredControllerInterface;
30
use Symfony\Component\HttpFoundation\Request;
31
use Symfony\Component\HttpFoundation\Response;
32
33
/**
34
 * Provides API for article-pages.
35
 */
36
class ArticlePageController extends RestController implements ClassResourceInterface, SecuredControllerInterface
37
{
38
    const DOCUMENT_TYPE = 'article_page';
39
40
    use RequestParametersTrait;
41
42
    /**
43
     * Returns single article-page.
44
     *
45
     * @param string $articleUuid
46
     * @param string $uuid
47
     * @param Request $request
48
     *
49
     * @return Response
50
     *
51
     * @throws ArticlePageNotFoundException
52
     */
53
    public function getAction($articleUuid, $uuid, Request $request)
54
    {
55
        $locale = $this->getRequestParameter($request, 'locale', true);
56
        $document = $this->getDocumentManager()->find(
57
            $uuid,
58
            $locale,
59
            [
60
                'load_ghost_content' => true,
61
                'load_shadow_content' => false,
62
            ]
63
        );
64
65
        if ($articleUuid !== $document->getParent()->getUuid()) {
66
            // it is required that the parent will be called to resolve the proxy.
67
            // this wont be done in the serialization process.
68
69
            throw new ArticlePageNotFoundException($uuid, $articleUuid);
70
        }
71
72
        return $this->handleView(
73
            $this->view($document)->setSerializationContext(
0 ignored issues
show
Bug introduced by
The method setSerializationContext() does not seem to exist on object<Sulu\Bundle\Artic...\ArticlePageController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
74
                SerializationContext::create()
75
                    ->setSerializeNull(true)
76
                    ->setGroups(['defaultPage', 'defaultArticlePage', 'smallArticle'])
77
            )
78
        );
79
    }
80
81
    /**
82
     * Create article-page.
83
     *
84
     * @param string $articleUuid
85
     * @param Request $request
86
     *
87
     * @return Response
88
     */
89 View Code Duplication
    public function postAction($articleUuid, 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...
90
    {
91
        $action = $request->get('action');
92
        $document = $this->getDocumentManager()->create(self::DOCUMENT_TYPE);
93
        $locale = $this->getRequestParameter($request, 'locale', true);
94
        $data = $request->request->all();
95
96
        $this->persistDocument($data, $document, $locale, $articleUuid);
97
        $this->handleActionParameter($action, $document->getParent(), $locale);
98
        $this->getDocumentManager()->flush();
99
100
        return $this->handleView(
101
            $this->view($document)->setSerializationContext(
0 ignored issues
show
Bug introduced by
The method setSerializationContext() does not seem to exist on object<Sulu\Bundle\Artic...\ArticlePageController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
102
                SerializationContext::create()
103
                    ->setSerializeNull(true)
104
                    ->setGroups(['defaultPage', 'defaultArticlePage', 'smallArticle'])
105
            )
106
        );
107
    }
108
109
    /**
110
     * Trigger a action for given article-page specified over get-action parameter.
111
     *
112
     * @Post("/articles/{articleUuid}/pages/{uuid}")
113
     *
114
     * @param string $uuid
115
     * @param Request $request
116
     *
117
     * @return Response
118
     */
119
    public function postTriggerAction($articleUuid, $uuid, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $articleUuid is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
120
    {
121
        // extract parameter
122
        $action = $this->getRequestParameter($request, 'action', true);
123
        $locale = $this->getRequestParameter($request, 'locale', true);
124
125
        // prepare vars
126
        $view = null;
127
        $data = null;
128
        $userId = $this->getUser()->getId();
129
130
        try {
131
            switch ($action) {
132 View Code Duplication
                case 'copy-locale':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
133
                    $destLocales = $this->getRequestParameter($request, 'dest', true);
134
                    $data = $this->getMapper()->copyLanguage($uuid, $userId, null, $locale, explode(',', $destLocales));
135
                    break;
136
                default:
137
                    throw new RestException('Unrecognized action: ' . $action);
138
            }
139
140
            // prepare view
141
            $view = $this->view($data);
142
            $view->setSerializationContext(
0 ignored issues
show
Bug introduced by
The method setSerializationContext() does not seem to exist on object<Sulu\Bundle\Artic...\ArticlePageController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
143
                SerializationContext::create()
144
                    ->setSerializeNull(true)
145
                    ->setGroups(['defaultPage', 'defaultArticlePage', 'smallArticle'])
146
            );
147
        } catch (RestException $exc) {
148
            $view = $this->view($exc->toArray(), 400);
149
        }
150
151
        return $this->handleView($view);
0 ignored issues
show
Documentation introduced by
$view is of type this<Sulu\Bundle\Article...\ArticlePageController>, but the function expects a object<FOS\RestBundle\View\View>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
152
    }
153
154
    /**
155
     * Update article-page.
156
     *
157
     * @param string $articleUuid
158
     * @param string $uuid
159
     * @param Request $request
160
     *
161
     * @return Response
162
     */
163 View Code Duplication
    public function putAction($articleUuid, $uuid, 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...
164
    {
165
        $locale = $this->getRequestParameter($request, 'locale', true);
166
        $action = $request->get('action');
167
        $data = $request->request->all();
168
169
        $document = $this->getDocumentManager()->find(
170
            $uuid,
171
            $locale,
172
            [
173
                'load_ghost_content' => false,
174
                'load_shadow_content' => false,
175
            ]
176
        );
177
178
        $this->get('sulu_hash.request_hash_checker')->checkHash($request, $document, $document->getUuid());
179
180
        $this->persistDocument($data, $document, $locale, $articleUuid);
181
        $this->handleActionParameter($action, $document->getParent(), $locale);
182
        $this->getDocumentManager()->flush();
183
184
        return $this->handleView(
185
            $this->view($document)->setSerializationContext(
0 ignored issues
show
Bug introduced by
The method setSerializationContext() does not seem to exist on object<Sulu\Bundle\Artic...\ArticlePageController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
186
                SerializationContext::create()
187
                    ->setSerializeNull(true)
188
                    ->setGroups(['defaultPage', 'defaultArticlePage', 'smallArticle'])
189
            )
190
        );
191
    }
192
193
    /**
194
     * Delete article-page.
195
     *
196
     * @param string $articleUuid
197
     * @param string $uuid
198
     * @param Request $request
199
     *
200
     * @return Response
201
     */
202
    public function deleteAction($articleUuid, $uuid, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $articleUuid is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
203
    {
204
        $locale = $this->getRequestParameter($request, 'locale', true);
205
206
        $documentManager = $this->getDocumentManager();
207
        $document = $documentManager->find($uuid, $locale);
208
        $documentManager->remove($document);
209
        $documentManager->flush();
210
211
        return $this->handleView($this->view(null));
0 ignored issues
show
Documentation introduced by
$this->view(null) is of type this<Sulu\Bundle\Article...\ArticlePageController>, but the function expects a object<FOS\RestBundle\View\View>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
212
    }
213
214
    /**
215
     * {@inheritdoc}
216
     */
217
    public function getSecurityContext()
218
    {
219
        return ArticleAdmin::SECURITY_CONTEXT;
220
    }
221
222
    /**
223
     * Persists the document using the given information.
224
     *
225
     * @param array $data
226
     * @param object $document
227
     * @param string $locale
228
     * @param string $articleUuid
229
     *
230
     * @throws InvalidFormException
231
     * @throws MissingParameterException
232
     * @throws ParameterNotAllowedException
233
     */
234
    private function persistDocument($data, $document, $locale, $articleUuid)
235
    {
236
        if (array_key_exists('title', $data)) {
237
            throw new ParameterNotAllowedException('title', ArticlePageDocument::class);
238
        }
239
240
        $article = $this->getDocumentManager()->find($articleUuid, $locale);
241
        if (!array_key_exists('template', $data)) {
242
            $data['template'] = $article->getStructureType();
243
        }
244
245
        $form = $this->createForm(
246
            ArticlePageDocumentType::class,
247
            $document,
248
            [
249
                // disable csrf protection, since we can't produce a token, because the form is cached on the client
250
                'csrf_protection' => false,
251
            ]
252
        );
253
        $form->submit($data, false);
254
255
        $document->setParent($article);
256
257
        if (!$form->isValid()) {
258
            throw new InvalidFormException($form);
259
        }
260
261
        $this->getDocumentManager()->persist(
262
            $document,
263
            $locale,
264
            [
265
                'user' => $this->getUser()->getId(),
266
                'clear_missing_content' => false,
267
                'auto_name' => false,
268
                'auto_rename' => false,
269
            ]
270
        );
271
    }
272
273
    /**
274
     * Returns document-manager.
275
     *
276
     * @return DocumentManagerInterface
277
     */
278
    protected function getDocumentManager()
279
    {
280
        return $this->get('sulu_document_manager.document_manager');
281
    }
282
283
    /**
284
     * @return ContentMapperInterface
285
     */
286
    protected function getMapper()
287
    {
288
        return $this->get('sulu.content.mapper');
289
    }
290
291
    /**
292
     * Delegates actions by given actionParameter, which can be retrieved from the request.
293
     *
294
     * @param string $actionParameter
295
     * @param object $document
296
     * @param string $locale
297
     */
298
    private function handleActionParameter($actionParameter, $document, $locale)
299
    {
300
        switch ($actionParameter) {
301
            case 'publish':
302
                $this->getDocumentManager()->publish($document, $locale);
303
                break;
304
        }
305
    }
306
}
307