Completed
Pull Request — develop (#343)
by Wachter
10:23
created

ArticleController::orderPages()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
ccs 0
cts 0
cp 0
cc 2
nc 2
nop 2
crap 6
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 Guzzle\Inflection\Inflector;
17
use JMS\Serializer\SerializationContext;
18
use ONGR\ElasticsearchBundle\Service\Manager;
19
use ONGR\ElasticsearchDSL\Query\Compound\BoolQuery;
20
use ONGR\ElasticsearchDSL\Query\FullText\MatchPhrasePrefixQuery;
21
use ONGR\ElasticsearchDSL\Query\FullText\MatchQuery;
22
use ONGR\ElasticsearchDSL\Query\MatchAllQuery;
23
use ONGR\ElasticsearchDSL\Query\TermLevel\IdsQuery;
24
use ONGR\ElasticsearchDSL\Query\TermLevel\RangeQuery;
25
use ONGR\ElasticsearchDSL\Query\TermLevel\TermQuery;
26
use ONGR\ElasticsearchDSL\Sort\FieldSort;
27
use Sulu\Bundle\ArticleBundle\Admin\ArticleAdmin;
28
use Sulu\Bundle\ArticleBundle\Document\ArticleDocument;
29
use Sulu\Bundle\ArticleBundle\ListBuilder\ElasticSearchFieldDescriptor;
30
use Sulu\Bundle\ArticleBundle\Metadata\ArticleViewDocumentIdTrait;
31
use Sulu\Component\Content\Form\Exception\InvalidFormException;
32
use Sulu\Component\Content\Mapper\ContentMapperInterface;
33
use Sulu\Component\DocumentManager\DocumentManagerInterface;
34
use Sulu\Component\DocumentManager\Metadata\BaseMetadataFactory;
35
use Sulu\Component\Rest\Exception\MissingParameterException;
36
use Sulu\Component\Rest\Exception\RestException;
37
use Sulu\Component\Rest\ListBuilder\FieldDescriptorInterface;
38
use Sulu\Component\Rest\ListBuilder\ListRepresentation;
39
use Sulu\Component\Rest\RequestParametersTrait;
40
use Sulu\Component\Rest\RestController;
41
use Sulu\Component\Security\Authorization\PermissionTypes;
42
use Sulu\Component\Security\Authorization\SecurityCondition;
43
use Sulu\Component\Security\SecuredControllerInterface;
44
use Symfony\Component\HttpFoundation\Request;
45
use Symfony\Component\HttpFoundation\Response;
46
47
/**
48
 * Provides API for articles.
49
 */
50
class ArticleController extends RestController implements ClassResourceInterface, SecuredControllerInterface
51
{
52
    const DOCUMENT_TYPE = 'article';
53
54
    use RequestParametersTrait;
55
    use ArticleViewDocumentIdTrait;
56
57
    /**
58
     * Create field-descriptor array.
59
     *
60
     * @return ElasticSearchFieldDescriptor[]
61
     */
62
    protected function getFieldDescriptors()
63
    {
64
        return [
65
            'uuid' => ElasticSearchFieldDescriptor::create('id', 'public.id')
66
                ->setDisabled(true)
67
                ->build(),
68
            'typeTranslation' => ElasticSearchFieldDescriptor::create('typeTranslation', 'sulu_article.list.type')
69
                ->setSortField('typeTranslation.raw')
70
                ->setDisabled(!$this->getParameter('sulu_article.display_tab_all'))
71
                ->build(),
72
            'title' => ElasticSearchFieldDescriptor::create('title', 'public.title')
73
                ->setSortField('title.raw')
74
                ->build(),
75
            'creatorFullName' => ElasticSearchFieldDescriptor::create('creatorFullName', 'sulu_article.list.creator')
76
                ->setSortField('creatorFullName.raw')
77
                ->build(),
78
            'changerFullName' => ElasticSearchFieldDescriptor::create('changerFullName', 'sulu_article.list.changer')
79
                ->setSortField('changerFullName.raw')
80
                ->build(),
81
            'authorFullName' => ElasticSearchFieldDescriptor::create('authorFullName', 'sulu_article.author')
82
                ->setSortField('authorFullName.raw')
83
                ->build(),
84
            'created' => ElasticSearchFieldDescriptor::create('created', 'public.created')
85
                ->setSortField('authored')
86
                ->setType('datetime')
87
                ->setDisabled(true)
88
                ->build(),
89
            'changed' => ElasticSearchFieldDescriptor::create('changed', 'public.changed')
90
                ->setSortField('authored')
91
                ->setType('datetime')
92
                ->setDisabled(true)
93
                ->build(),
94
            'authored' => ElasticSearchFieldDescriptor::create('authored', 'sulu_article.authored')
95
                ->setSortField('authored')
96
                ->setType('datetime')
97
                ->build(),
98 12
            'localizationState' => ElasticSearchFieldDescriptor::create('localizationState')
99
                ->setDisabled(true)
100 12
                ->build(),
101
            'published' => ElasticSearchFieldDescriptor::create('published')
102 12
                ->setDisabled(true)
103
                ->build(),
104
            'publishedState' => ElasticSearchFieldDescriptor::create('publishedState')
105 12
                ->setDisabled(true)
106 12
                ->build(),
107 12
            'routePath' => ElasticSearchFieldDescriptor::create('routePath')
108
                ->setDisabled(true)
109 12
                ->build(),
110 12
        ];
111
    }
112 12
113 12
    /**
114
     * Returns fields.
115
     *
116 12
     * @return Response
117 1
     */
118 1
    public function cgetFieldsAction()
119
    {
120
        $fieldDescriptors = $this->getFieldDescriptors();
121 12
122 12
        return $this->handleView($this->view(array_values($fieldDescriptors)));
0 ignored issues
show
Documentation introduced by
$this->view(array_values($fieldDescriptors)) is of type this<Sulu\Bundle\Article...ller\ArticleController>, 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...
123
    }
124 2
125
    /**
126
     * Returns list of articles.
127 12
     *
128 10
     * @param Request $request
129
     *
130
     * @return Response
131 12
     */
132 1
    public function cgetAction(Request $request)
133 1
    {
134 1
        $locale = $this->getRequestParameter($request, 'locale', true);
135 1
136 1
        $restHelper = $this->get('sulu_core.list_rest_helper');
137
138
        /** @var Manager $manager */
139 12
        $manager = $this->get('es.manager.default');
140 1
        $repository = $manager->getRepository($this->get('sulu_article.view_document.factory')->getClass('article'));
141
        $search = $repository->createSearch();
142
143 12
        $limit = (int) $restHelper->getLimit();
144
        $page = (int) $restHelper->getPage();
145
146
        if (null !== $locale) {
147 12
            $search->addQuery(new TermQuery('locale', $locale));
148
        }
149 12
150 1
        if (count($ids = array_filter(explode(',', $request->get('ids', ''))))) {
151 1
            $search->addQuery(new IdsQuery($this->getViewDocumentIds($ids, $locale)));
152
            $limit = count($ids);
153
        }
154
155 12
        if (!empty($searchPattern = $restHelper->getSearchPattern())
156 12
            && 0 < count($searchFields = $restHelper->getSearchFields())
157
        ) {
158 12
            $boolQuery = new BoolQuery();
159 12
            foreach ($searchFields as $searchField) {
160 10
                $boolQuery->add(new MatchPhrasePrefixQuery($searchField, $searchPattern), BoolQuery::SHOULD);
161 1
            }
162
            $search->addQuery($boolQuery);
163 12
        }
164
165
        if (null !== ($type = $request->get('type'))) {
166
            $search->addQuery(new TermQuery('type', $type));
167 12
        }
168 1
169 1
        if ($contactId = $request->get('contactId')) {
170
            $boolQuery = new BoolQuery();
171
            $boolQuery->add(new MatchQuery('changer_contact_id', $contactId), BoolQuery::SHOULD);
172 12
            $boolQuery->add(new MatchQuery('creator_contact_id', $contactId), BoolQuery::SHOULD);
173 12
            $boolQuery->add(new MatchQuery('author_id', $contactId), BoolQuery::SHOULD);
174 12
            $search->addQuery($boolQuery);
175 12
        }
176 12
177 12
        if ($categoryId = $request->get('categoryId')) {
178 12
            $search->addQuery(new TermQuery('excerpt.categories.id', $categoryId), BoolQuery::MUST);
179 12
        }
180 12
181 12
        if ($tagId = $request->get('tagId')) {
182
            $search->addQuery(new TermQuery('excerpt.tags.id', $tagId), BoolQuery::MUST);
183
        }
184
185
        if ($pageId = $request->get('pageId')) {
186
            $search->addQuery(new TermQuery('parent_page_uuid', $pageId), BoolQuery::MUST);
187
        }
188
189
        if ($workflowStage = $request->get('workflowStage')) {
190
            $search->addQuery(new TermQuery('published_state', 'published' === $workflowStage), BoolQuery::MUST);
0 ignored issues
show
Documentation introduced by
'published' === $workflowStage is of type boolean, but the function expects a string.

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...
191
        }
192
193
        if ($this->getBooleanRequestParameter($request, 'exclude-shadows', false, false)) {
194
            $search->addQuery(new TermQuery('localization_state.state', 'shadow'), BoolQuery::MUST_NOT);
195 9
        }
196
197 9
        if ($this->getBooleanRequestParameter($request, 'exclude-ghosts', false, false)) {
198 9
            $search->addQuery(new TermQuery('localization_state.state', 'ghost'), BoolQuery::MUST_NOT);
199 9
        }
200 9
201
        $authoredFrom = $request->get('authoredFrom');
202 9
        $authoredTo = $request->get('authoredTo');
203
        if ($authoredFrom || $authoredTo) {
204
            $search->addQuery($this->getRangeQuery('authored', $authoredFrom, $authoredTo), BoolQuery::MUST);
205
        }
206
207 9
        if (null === $search->getQueries()) {
208 9
            $search->addQuery(new MatchAllQuery());
209 9
        }
210 9
211 9
        if (null !== $restHelper->getSortColumn() &&
212
            $sortField = $this->getSortFieldName($restHelper->getSortColumn())
213
        ) {
214
            $search->addSort(
215
                new FieldSort($sortField, $restHelper->getSortOrder())
216
            );
217
        }
218
219
        $fieldDescriptors = $this->getFieldDescriptors();
220
221
        if ($limit) {
222
            $search->setSize($limit);
223 51
            $search->setFrom(($page - 1) * $limit);
224
225 51
            $fields = array_merge(
226 51
                $restHelper->getFields() ?: [],
227 51
                ['id', 'localizationState', 'publishedState', 'published']
228 51
            );
229
            $fieldDescriptors = array_filter(
230 51
                $fieldDescriptors,
231 51
                function (FieldDescriptorInterface $fieldDescriptor) use ($fields) {
232 51
                    return in_array($fieldDescriptor->getName(), $fields);
233
                }
234 51
            );
235 51
        } else {
236 51
            $search->setSize(1000);
237 51
            $search->setScroll('1m');
238 51
        }
239
240
        $searchResult = $repository->findRaw($search);
241
        $result = [];
242
        foreach ($searchResult as $document) {
243
            $documentData = $this->normalize($document['_source'], $fieldDescriptors);
244
            if (false !== ($index = array_search($documentData['id'], $ids))) {
245
                $result[$index] = $documentData;
246
            } else {
247
                $result[] = $documentData;
248
            }
249
        }
250
251 9
        if (count($ids)) {
252
            ksort($result);
253 9
            $result = array_values($result);
254 9
        }
255 9
256
        $count = $searchResult->count();
257 9
258 9
        return $this->handleView(
259 9
            $this->view(
0 ignored issues
show
Documentation introduced by
$this->view(new \Sulu\Co...$page, $limit, $count)) is of type this<Sulu\Bundle\Article...ller\ArticleController>, 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...
260
                new ListRepresentation(
261 9
                    $result,
262
                    'articles',
263
                    'get_articles',
264
                    $request->query->all(),
265
                    $page,
266 9
                    $limit,
267
                    $count
268 9
                )
269 9
            )
270 9
        );
271
    }
272 9
273 9
    /**
274 9
     * @param FieldDescriptorInterface[] $fieldDescriptors
275 9
     */
276 9
    private function normalize(array $document, array $fieldDescriptors)
277
    {
278
        $result = [];
279
        foreach ($fieldDescriptors as $fieldDescriptor) {
280
            $property = Inflector::getDefault()->snake($fieldDescriptor->getName());
281
            if ('id' === $property) {
282
                $property = 'uuid';
283
            }
284
285
            $result[$fieldDescriptor->getName()] = array_key_exists($property, $document) ? $document[$property] : null;
286
        }
287
288 1
        return $result;
289
    }
290 1
291
    /**
292 1
     * Returns query to filter by given range.
293 1
     *
294 1
     * @param string $field
295 1
     * @param string $from
296 1
     * @param string $to
297
     *
298
     * @return RangeQuery
299 1
     */
300
    private function getRangeQuery($field, $from, $to)
301
    {
302
        return new RangeQuery($field, array_filter(['gte' => $from, 'lte' => $to]));
303
    }
304
305
    /**
306
     * Returns single article.
307
     *
308
     * @param string $uuid
309 1
     * @param Request $request
310
     *
311 1
     * @return Response
312 1
     */
313 1
    public function getAction($uuid, Request $request)
314 1
    {
315
        $locale = $this->getRequestParameter($request, 'locale', true);
316 1
        $document = $this->getDocumentManager()->find(
317
            $uuid,
318
            $locale
319
        );
320
321
        return $this->handleView(
322
            $this->view($document)->setSerializationContext(
0 ignored issues
show
Bug introduced by
The method setSerializationContext() does not seem to exist on object<Sulu\Bundle\Artic...ller\ArticleController>.

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...
323
                SerializationContext::create()
324
                    ->setSerializeNull(true)
325
                    ->setGroups(['defaultPage', 'defaultArticle', 'smallArticlePage'])
326
            )
327
        );
328
    }
329 2
330
    /**
331
     * Create article.
332 2
     *
333 2
     * @param Request $request
334
     *
335
     * @return Response
336 2
     */
337 2 View Code Duplication
    public function postAction(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...
338 2
    {
339
        $action = $request->get('action');
340
        $document = $this->getDocumentManager()->create(self::DOCUMENT_TYPE);
341
        $locale = $this->getRequestParameter($request, 'locale', true);
342 2
        $data = $request->request->all();
343
344
        $this->persistDocument($data, $document, $locale);
345
        $this->handleActionParameter($action, $document, $locale);
346
        $this->getDocumentManager()->flush();
347
348
        return $this->handleView(
349 2
            $this->view($document)->setSerializationContext(
0 ignored issues
show
Bug introduced by
The method setSerializationContext() does not seem to exist on object<Sulu\Bundle\Artic...ller\ArticleController>.

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...
350
                SerializationContext::create()
351
                    ->setSerializeNull(true)
352
                    ->setGroups(['defaultPage', 'defaultArticle', 'smallArticlePage'])
353
            )
354 2
        );
355 1
    }
356 1
357
    /**
358 1
     * Update articles.
359 1
     *
360 1
     * @param Request $request
361 1
     * @param string  $uuid
362 1
     *
363
     * @return Response
364
     */
365 View Code Duplication
    public function putAction(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...
366 1
    {
367
        $locale = $this->getRequestParameter($request, 'locale', true);
368 1
        $action = $request->get('action');
369 1
        $data = $request->request->all();
370 1
371
        $document = $this->getDocumentManager()->find(
372
            $uuid,
373
            $locale,
374
            [
375
                'load_ghost_content' => false,
376
                'load_shadow_content' => false,
377
            ]
378 1
        );
379 1
380 1
        $this->get('sulu_hash.request_hash_checker')->checkHash($request, $document, $document->getUuid());
381 1
382
        $this->persistDocument($data, $document, $locale);
383 1
        $this->handleActionParameter($action, $document, $locale);
384 1
        $this->getDocumentManager()->flush();
385
386
        return $this->handleView(
387
            $this->view($document)->setSerializationContext(
0 ignored issues
show
Bug introduced by
The method setSerializationContext() does not seem to exist on object<Sulu\Bundle\Artic...ller\ArticleController>.

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...
388
                SerializationContext::create()
389
                    ->setSerializeNull(true)
390 2
                    ->setGroups(['defaultPage', 'defaultArticle', 'smallArticlePage'])
391 2
            )
392 2
        );
393 2
    }
394 2
395
    /**
396
     * Deletes multiple documents.
397
     *
398
     * @param Request $request
399
     *
400 2
     * @return Response
401
     */
402
    public function cdeleteAction(Request $request)
403
    {
404
        $ids = array_filter(explode(',', $request->get('ids', '')));
405
406
        $documentManager = $this->getDocumentManager();
407
        foreach ($ids as $id) {
408
            $document = $documentManager->find($id);
409 1
            $documentManager->remove($document);
410
            $documentManager->flush();
411 1
        }
412
413 1
        return $this->handleView($this->view(null));
0 ignored issues
show
Documentation introduced by
$this->view(null) is of type this<Sulu\Bundle\Article...ller\ArticleController>, 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...
414 1
    }
415 1
416
    /**
417 1
     * Deletes multiple documents.
418
     *
419
     * @param string $id
420
     *
421
     * @return Response
422 52
     */
423
    public function deleteAction($id)
424 52
    {
425
        $documentManager = $this->getDocumentManager();
426
        $document = $documentManager->find($id);
427
        $documentManager->remove($document);
428
        $documentManager->flush();
429
430
        return $this->handleView($this->view(null));
0 ignored issues
show
Documentation introduced by
$this->view(null) is of type this<Sulu\Bundle\Article...ller\ArticleController>, 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...
431
    }
432
433
    /**
434
     * Trigger a action for given article specified over get-action parameter.
435
     *
436
     * @Post("/articles/{uuid}")
437 51
     *
438
     * @param string  $uuid
439 51
     * @param Request $request
440 51
     *
441 51
     * @return Response
442
     */
443
    public function postTriggerAction($uuid, Request $request)
444 51
    {
445
        // extract parameter
446
        $action = $this->getRequestParameter($request, 'action', true);
447 51
        $locale = $this->getRequestParameter($request, 'locale', true);
448
449 51
        // prepare vars
450
        $view = null;
451
        $data = null;
452
        $userId = $this->getUser()->getId();
453 51
454
        try {
455
            switch ($action) {
456
                case 'unpublish':
457 51
                    $document = $this->getDocumentManager()->find($uuid, $locale);
458 51
                    $this->getDocumentManager()->unpublish($document, $locale);
459 51
                    $this->getDocumentManager()->flush();
460
461 51
                    $data = $this->getDocumentManager()->find($uuid, $locale);
462
463
                    break;
464
                case 'remove-draft':
465 51
                    $data = $this->getDocumentManager()->find($uuid, $locale);
466
                    $this->getDocumentManager()->removeDraft($data, $locale);
467
                    $this->getDocumentManager()->flush();
468
469
                    break;
470
                case 'copy-locale':
471
                    $destLocales = $this->getRequestParameter($request, 'dest', true);
472 51
                    $destLocales = explode(',', $destLocales);
473
474 51
                    $securityChecker = $this->get('sulu_security.security_checker');
475
                    foreach ($destLocales as $destLocale) {
476
                        $securityChecker->checkPermission(
477
                            new SecurityCondition($this->getSecurityContext(), $destLocale),
478
                            PermissionTypes::EDIT
479
                        );
480 1
                    }
481
482 1
                    $this->getMapper()->copyLanguage($uuid, $userId, null, $locale, $destLocales);
483
484
                    $data = $this->getDocumentManager()->find($uuid, $locale);
485
486
                    break;
487
                case 'copy':
488
                    /** @var ArticleDocument $document */
489
                    $document = $this->getDocumentManager()->find($uuid, $locale);
490
                    $copiedPath = $this->getDocumentManager()->copy($document, dirname($document->getPath()));
491
                    $this->getDocumentManager()->flush();
492 51
493
                    $data = $this->getDocumentManager()->find($copiedPath, $locale);
494
495 51
                    break;
496 17
                case 'order':
497 17
                    $this->orderPages($this->getRequestParameter($request, 'pages', true), $locale);
0 ignored issues
show
Documentation introduced by
$this->getRequestParamet...request, 'pages', true) is of type string, but the function expects a array.

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...
498
                    $this->getDocumentManager()->flush();
499 51
                    $this->getDocumentManager()->clear();
500
501
                    $data = $this->getDocumentManager()->find($uuid, $locale);
502
503
                    break;
504
                default:
505
                    throw new RestException('Unrecognized action: ' . $action);
506
            }
507
508 1
            // prepare view
509
            $view = $this->view($data);
510 1
            $view->setSerializationContext(
0 ignored issues
show
Bug introduced by
The method setSerializationContext() does not seem to exist on object<Sulu\Bundle\Artic...ller\ArticleController>.

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...
511 1
                SerializationContext::create()
512 1
                    ->setSerializeNull(true)
513 1
                    ->setGroups(['defaultPage', 'defaultArticle', 'smallArticlePage'])
514
            );
515
        } catch (RestException $exc) {
516 1
            $view = $this->view($exc->toArray(), 400);
517
        }
518
519
        return $this->handleView($view);
0 ignored issues
show
Documentation introduced by
$view is of type this<Sulu\Bundle\Article...ller\ArticleController>, 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...
520
    }
521
522
    /**
523
     * Ordering given pages.
524
     *
525
     * @param array $pages
526
     * @param string $locale
527
     */
528
    private function orderPages(array $pages, $locale)
529
    {
530
        $documentManager = $this->getDocumentManager();
531
532
        for ($i = 0; $i < count($pages); ++$i) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
533
            $document = $documentManager->find($pages[$i], $locale);
534
            $documentManager->reorder($document, null);
535
        }
536
    }
537
538
    /**
539
     * {@inheritdoc}
540
     */
541
    public function getSecurityContext()
542
    {
543
        return ArticleAdmin::SECURITY_CONTEXT;
544
    }
545
546
    /**
547
     * Persists the document using the given Formation.
548
     *
549
     * @param array  $data
550
     * @param object $document
551
     * @param string $locale
552
     *
553
     * @throws InvalidFormException
554
     * @throws MissingParameterException
555
     */
556
    private function persistDocument($data, $document, $locale)
557
    {
558
        $formType = $this->getMetadataFactory()->getMetadataForAlias('article')->getFormType();
559
        $form = $this->createForm(
560
            $formType,
561
            $document,
562
            [
563
                // disable csrf protection, since we can't produce a token, because the form is cached on the client
564
                'csrf_protection' => false,
565
            ]
566
        );
567
        $form->submit($data, false);
568
569
        if (!$form->isValid()) {
570
            throw new InvalidFormException($form);
571
        }
572
573
        if (array_key_exists('author', $data) && null === $data['author']) {
574
            $document->setAuthor(null);
575
        }
576
577
        if (array_key_exists('additionalWebspaces', $data) && null === $data['additionalWebspaces']) {
578
            $document->setAdditionalWebspaces(null);
579
        }
580
581
        $this->getDocumentManager()->persist(
582
            $document,
583
            $locale,
584
            [
585
                'user' => $this->getUser()->getId(),
586
                'clear_missing_content' => false,
587
            ]
588
        );
589
    }
590
591
    /**
592
     * Returns document-manager.
593
     *
594
     * @return DocumentManagerInterface
595
     */
596
    protected function getDocumentManager()
597
    {
598
        return $this->get('sulu_document_manager.document_manager');
599
    }
600
601
    /**
602
     * @return ContentMapperInterface
603
     */
604
    protected function getMapper()
605
    {
606
        return $this->get('sulu.content.mapper');
607
    }
608
609
    /**
610
     * Delegates actions by given actionParameter, which can be retrieved from the request.
611
     *
612
     * @param string $actionParameter
613
     * @param object $document
614
     * @param string $locale
615
     */
616
    private function handleActionParameter($actionParameter, $document, $locale)
617
    {
618
        switch ($actionParameter) {
619
            case 'publish':
620
                $this->getDocumentManager()->publish($document, $locale);
621
622
                break;
623
        }
624
    }
625
626
    /**
627
     * @param string $sortBy
628
     *
629
     * @return null|string
630
     */
631
    private function getSortFieldName($sortBy)
632
    {
633
        $sortBy = Inflector::getDefault()->snake($sortBy);
634
        $fieldDescriptors = $this->getFieldDescriptors();
635
636
        if (array_key_exists($sortBy, $fieldDescriptors)) {
637
            return $fieldDescriptors[$sortBy]->getSortField();
638
        }
639
640
        return null;
641
    }
642
643
    /**
644
     * @return BaseMetadataFactory
645
     */
646
    protected function getMetadataFactory()
647
    {
648
        return $this->get('sulu_document_manager.metadata_factory.base');
649
    }
650
}
651