Completed
Pull Request — develop (#233)
by Wachter
45:40 queued 30:46
created

ArticleController::getSecurityContext()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
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 ONGR\ElasticsearchBundle\Service\Manager;
18
use ONGR\ElasticsearchDSL\Query\Compound\BoolQuery;
19
use ONGR\ElasticsearchDSL\Query\FullText\MatchPhraseQuery;
20
use ONGR\ElasticsearchDSL\Query\FullText\MatchQuery;
21
use ONGR\ElasticsearchDSL\Query\MatchAllQuery;
22
use ONGR\ElasticsearchDSL\Query\TermLevel\IdsQuery;
23
use ONGR\ElasticsearchDSL\Query\TermLevel\RangeQuery;
24
use ONGR\ElasticsearchDSL\Query\TermLevel\TermQuery;
25
use ONGR\ElasticsearchDSL\Sort\FieldSort;
26
use Sulu\Bundle\ArticleBundle\Admin\ArticleAdmin;
27
use Sulu\Bundle\ArticleBundle\Document\ArticleDocument;
28
use Sulu\Bundle\ArticleBundle\Document\Form\ArticleDocumentType;
29
use Sulu\Bundle\ArticleBundle\Metadata\ArticleViewDocumentIdTrait;
30
use Sulu\Component\Content\Form\Exception\InvalidFormException;
31
use Sulu\Component\Content\Mapper\ContentMapperInterface;
32
use Sulu\Component\DocumentManager\DocumentManagerInterface;
33
use Sulu\Component\Rest\Exception\MissingParameterException;
34
use Sulu\Component\Rest\Exception\RestException;
35
use Sulu\Component\Rest\ListBuilder\FieldDescriptor;
36
use Sulu\Component\Rest\ListBuilder\ListRepresentation;
37
use Sulu\Component\Rest\RequestParametersTrait;
38
use Sulu\Component\Rest\RestController;
39
use Sulu\Component\Security\Authorization\PermissionTypes;
40
use Sulu\Component\Security\Authorization\SecurityCondition;
41
use Sulu\Component\Security\SecuredControllerInterface;
42
use Symfony\Component\HttpFoundation\Request;
43
use Symfony\Component\HttpFoundation\Response;
44
45
/**
46
 * Provides API for articles.
47
 */
48
class ArticleController extends RestController implements ClassResourceInterface, SecuredControllerInterface
49
{
50
    const DOCUMENT_TYPE = 'article';
51
52
    use RequestParametersTrait;
53
    use ArticleViewDocumentIdTrait;
54
55
    /**
56
     * Create field-descriptor array.
57
     *
58
     * @return FieldDescriptor[]
59
     */
60
    private function getFieldDescriptors()
61
    {
62
        return [
63
            'uuid' => new FieldDescriptor('uuid', 'public.id', true),
64
            'typeTranslation' => new FieldDescriptor(
65
                'typeTranslation',
66
                'sulu_article.list.type',
67
                !$this->getParameter('sulu_article.display_tab_all'),
68
                false
69
            ),
70
            'title' => new FieldDescriptor('title', 'public.title', false, true),
71
            'creatorFullName' => new FieldDescriptor('creatorFullName', 'sulu_article.list.creator', true, false),
72
            'changerFullName' => new FieldDescriptor('changerFullName', 'sulu_article.list.changer', false, false),
73
            'authorFullName' => new FieldDescriptor('authorFullName', 'sulu_article.author', false, false),
74
            'created' => new FieldDescriptor('created', 'public.created', true, false, 'datetime'),
75
            'changed' => new FieldDescriptor('changed', 'public.changed', false, false, 'datetime'),
76
            'authored' => new FieldDescriptor('authored', 'sulu_article.authored', false, false, 'date'),
77
        ];
78
    }
79
80
    /**
81
     * Returns fields.
82
     *
83
     * @return Response
84
     */
85
    public function cgetFieldsAction()
86
    {
87
        $fieldDescriptors = $this->getFieldDescriptors();
88
89
        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...
90
    }
91
92
    /**
93
     * Returns list of articles.
94
     *
95
     * @param Request $request
96
     *
97
     * @return Response
98 12
     */
99
    public function cgetAction(Request $request)
100 12
    {
101
        $locale = $this->getRequestParameter($request, 'locale', true);
102 12
103
        $restHelper = $this->get('sulu_core.list_rest_helper');
104
105 12
        /** @var Manager $manager */
106 12
        $manager = $this->get('es.manager.default');
107 12
        $repository = $manager->getRepository($this->get('sulu_article.view_document.factory')->getClass('article'));
108
        $search = $repository->createSearch();
109 12
110 12
        $limit = (int) $restHelper->getLimit();
111
        $page = (int) $restHelper->getPage();
112 12
113 12
        if (null !== $locale) {
114
            $search->addQuery(new TermQuery('locale', $locale));
115
        }
116 12
117 1
        if (count($ids = array_filter(explode(',', $request->get('ids', ''))))) {
118 1
            $search->addQuery(new IdsQuery($this->getViewDocumentIds($ids, $locale)));
119
            $limit = count($ids);
120
        }
121 12
122 12
        if (!empty($searchPattern = $restHelper->getSearchPattern())
123
            && 0 < count($searchFields = $restHelper->getSearchFields())
124 2
        ) {
125
            $boolQuery = new BoolQuery();
126
            foreach ($searchFields as $searchField) {
127 12
                $boolQuery->add(new MatchPhraseQuery($searchField, $searchPattern), BoolQuery::SHOULD);
128 10
            }
129
            $search->addQuery($boolQuery);
130
        }
131 12
132 1
        if (null !== ($type = $request->get('type'))) {
133 1
            $search->addQuery(new TermQuery('type', $type));
134 1
        }
135 1
136 1
        if ($contactId = $request->get('contactId')) {
137
            $boolQuery = new BoolQuery();
138
            $boolQuery->add(new MatchQuery('changer_contact_id', $contactId), BoolQuery::SHOULD);
139 12
            $boolQuery->add(new MatchQuery('creator_contact_id', $contactId), BoolQuery::SHOULD);
140 1
            $boolQuery->add(new MatchQuery('author_id', $contactId), BoolQuery::SHOULD);
141
            $search->addQuery($boolQuery);
142
        }
143 12
144
        if ($categoryId = $request->get('categoryId')) {
145
            $search->addQuery(new TermQuery('excerpt.categories.id', $categoryId), BoolQuery::MUST);
146
        }
147 12
148
        if ($tagId = $request->get('tagId')) {
149 12
            $search->addQuery(new TermQuery('excerpt.tags.id', $tagId), BoolQuery::MUST);
150 1
        }
151 1
152
        if ($pageId = $request->get('pageId')) {
153
            $search->addQuery(new TermQuery('parent_page_uuid', $pageId), BoolQuery::MUST);
154
        }
155 12
156 12
        if ($workflowStage = $request->get('workflowStage')) {
157
            $search->addQuery(new TermQuery('published_state', $workflowStage === 'published'), BoolQuery::MUST);
0 ignored issues
show
Documentation introduced by
$workflowStage === 'published' 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...
158 12
        }
159 12
160 10
        $authoredFrom = $request->get('authoredFrom');
161 1
        $authoredTo = $request->get('authoredTo');
162
        if ($authoredFrom || $authoredTo) {
163 12
            $search->addQuery($this->getRangeQuery('authored', $authoredFrom, $authoredTo), BoolQuery::MUST);
164
        }
165
166
        if (null === $search->getQueries()) {
167 12
            $search->addQuery(new MatchAllQuery());
168 1
        }
169 1
170
        if (null !== $restHelper->getSortColumn()) {
171
            $search->addSort(
172 12
                new FieldSort($this->uncamelize($restHelper->getSortColumn()), $restHelper->getSortOrder())
173 12
            );
174 12
        }
175 12
176 12
        $search->setSize($limit);
177 12
        $search->setFrom(($page - 1) * $limit);
178 12
179 12
        $result = [];
180 12
        $searchResult = $repository->findDocuments($search);
181 12
        foreach ($searchResult as $document) {
182
            if (false !== ($index = array_search($document->getUuid(), $ids))) {
183
                $result[$index] = $document;
184
            } else {
185
                $result[] = $document;
186
            }
187
        }
188
189
        if (count($ids)) {
190
            ksort($result);
191
            $result = array_values($result);
192
        }
193
194
        return $this->handleView(
195 9
            $this->view(
0 ignored issues
show
Documentation introduced by
$this->view(new \Sulu\Co...searchResult->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...
196
                new ListRepresentation(
197 9
                    $result,
198 9
                    'articles',
199 9
                    'get_articles',
200 9
                    $request->query->all(),
201
                    $page,
202 9
                    $limit,
203
                    $searchResult->count()
204
                )
205
            )
206
        );
207 9
    }
208 9
209 9
    /**
210 9
     * Returns query to filter by given range.
211 9
     *
212
     * @param string $field
213
     * @param string $from
214
     * @param string $to
215
     *
216
     * @return RangeQuery
217
     */
218
    private function getRangeQuery($field, $from, $to)
219
    {
220
        return new RangeQuery($field, array_filter(['gte' => $from, 'lte' => $to]));
221
    }
222
223 51
    /**
224
     * Returns single article.
225 51
     *
226 51
     * @param string  $uuid
227 51
     * @param Request $request
228 51
     *
229
     * @return Response
230 51
     */
231 51
    public function getAction($uuid, Request $request)
232 51
    {
233
        $locale = $this->getRequestParameter($request, 'locale', true);
234 51
        $document = $this->getDocumentManager()->find(
235 51
            $uuid,
236 51
            $locale,
237 51
            [
238 51
                'load_ghost_content' => true,
239
                'load_shadow_content' => false,
240
            ]
241
        );
242
243
        return $this->handleView(
244
            $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...
245
                SerializationContext::create()
246
                    ->setSerializeNull(true)
247
                    ->setGroups(['defaultPage', 'defaultArticle', 'smallArticlePage'])
248
            )
249
        );
250
    }
251 9
252
    /**
253 9
     * Create article.
254 9
     *
255 9
     * @param Request $request
256
     *
257 9
     * @return Response
258 9
     */
259 9 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...
260
    {
261 9
        $action = $request->get('action');
262
        $document = $this->getDocumentManager()->create(self::DOCUMENT_TYPE);
263
        $locale = $this->getRequestParameter($request, 'locale', true);
264
        $data = $request->request->all();
265
266 9
        $this->persistDocument($data, $document, $locale);
267
        $this->handleActionParameter($action, $document, $locale);
268 9
        $this->getDocumentManager()->flush();
269 9
270 9
        return $this->handleView(
271
            $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...
272 9
                SerializationContext::create()
273 9
                    ->setSerializeNull(true)
274 9
                    ->setGroups(['defaultPage', 'defaultArticle', 'smallArticlePage'])
275 9
            )
276 9
        );
277
    }
278
279
    /**
280
     * Update articles.
281
     *
282
     * @param Request $request
283
     * @param string  $uuid
284
     *
285
     * @return Response
286
     */
287 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...
288 1
    {
289
        $locale = $this->getRequestParameter($request, 'locale', true);
290 1
        $action = $request->get('action');
291
        $data = $request->request->all();
292 1
293 1
        $document = $this->getDocumentManager()->find(
294 1
            $uuid,
295 1
            $locale,
296 1
            [
297
                'load_ghost_content' => false,
298
                'load_shadow_content' => false,
299 1
            ]
300
        );
301
302
        $this->get('sulu_hash.request_hash_checker')->checkHash($request, $document, $document->getUuid());
303
304
        $this->persistDocument($data, $document, $locale);
305
        $this->handleActionParameter($action, $document, $locale);
306
        $this->getDocumentManager()->flush();
307
308
        return $this->handleView(
309 1
            $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...
310
                SerializationContext::create()
311 1
                    ->setSerializeNull(true)
312 1
                    ->setGroups(['defaultPage', 'defaultArticle', 'smallArticlePage'])
313 1
            )
314 1
        );
315
    }
316 1
317
    /**
318
     * Deletes multiple documents.
319
     *
320
     * @param Request $request
321
     *
322
     * @return Response
323
     */
324
    public function cdeleteAction(Request $request)
325
    {
326
        $ids = array_filter(explode(',', $request->get('ids', '')));
327
328
        $documentManager = $this->getDocumentManager();
329 2
        foreach ($ids as $id) {
330
            $document = $documentManager->find($id);
331
            $documentManager->remove($document);
332 2
            $documentManager->flush();
333 2
        }
334
335
        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...
336 2
    }
337 2
338 2
    /**
339
     * Deletes multiple documents.
340
     *
341
     * @param string $id
342 2
     *
343
     * @return Response
344
     */
345
    public function deleteAction($id)
346
    {
347
        $documentManager = $this->getDocumentManager();
348
        $document = $documentManager->find($id);
349 2
        $documentManager->remove($document);
350
        $documentManager->flush();
351
352
        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...
353
    }
354 2
355 1
    /**
356 1
     * Trigger a action for given article specified over get-action parameter.
357
     *
358 1
     * @Post("/articles/{uuid}")
359 1
     *
360 1
     * @param string  $uuid
361 1
     * @param Request $request
362 1
     *
363
     * @return Response
364
     */
365
    public function postTriggerAction($uuid, Request $request)
366 1
    {
367
        // extract parameter
368 1
        $action = $this->getRequestParameter($request, 'action', true);
369 1
        $locale = $this->getRequestParameter($request, 'locale', true);
370 1
371
        // prepare vars
372
        $view = null;
373
        $data = null;
374
        $userId = $this->getUser()->getId();
375
376
        try {
377
            switch ($action) {
378 1
                case 'unpublish':
379 1
                    $document = $this->getDocumentManager()->find($uuid, $locale);
380 1
                    $this->getDocumentManager()->unpublish($document, $locale);
381 1
                    $this->getDocumentManager()->flush();
382
383 1
                    $data = $this->getDocumentManager()->find($uuid, $locale);
384 1
                    break;
385
                case 'remove-draft':
386
                    $data = $this->getDocumentManager()->find($uuid, $locale);
387
                    $this->getDocumentManager()->removeDraft($data, $locale);
388
                    $this->getDocumentManager()->flush();
389
                    break;
390 2
                case 'copy-locale':
391 2
                    $destLocales = $this->getRequestParameter($request, 'dest', true);
392 2
                    $destLocales = explode(',', $destLocales);
393 2
394 2
                    $securityChecker = $this->get('sulu_security.security_checker');
395
                    foreach ($destLocales as $destLocale) {
396
                        $securityChecker->checkPermission(
397
                            new SecurityCondition($this->getSecurityContext(), $destLocale),
398
                            PermissionTypes::EDIT
399
                        );
400 2
                    }
401
402
                    $this->getMapper()->copyLanguage($uuid, $userId, null, $locale, $destLocales);
403
404
                    $data = $this->getDocumentManager()->find($uuid, $locale);
405
                    break;
406
                case 'copy':
407
                    /** @var ArticleDocument $document */
408
                    $document = $this->getDocumentManager()->find($uuid, $locale);
409 1
                    $copiedPath = $this->getDocumentManager()->copy($document, dirname($document->getPath()));
410
                    $this->getDocumentManager()->flush();
411 1
412
                    $data = $this->getDocumentManager()->find($copiedPath, $locale);
413 1
                    break;
414 1
                case 'order':
415 1
                    $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...
416
                    $this->getDocumentManager()->flush();
417 1
                    $this->getDocumentManager()->clear();
418
419
                    $data = $this->getDocumentManager()->find($uuid, $locale);
420
                    break;
421
                default:
422 52
                    throw new RestException('Unrecognized action: ' . $action);
423
            }
424 52
425
            // prepare view
426
            $view = $this->view($data);
427
            $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...
428
                SerializationContext::create()
429
                    ->setSerializeNull(true)
430
                    ->setGroups(['defaultPage', 'defaultArticle', 'smallArticlePage'])
431
            );
432
        } catch (RestException $exc) {
433
            $view = $this->view($exc->toArray(), 400);
434
        }
435
436
        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...
437 51
    }
438
439 51
    /**
440 51
     * Ordering given pages.
441 51
     *
442
     * @param array $pages
443
     * @param string $locale
444 51
     */
445
    private function orderPages(array $pages, $locale)
446
    {
447 51
        $documentManager = $this->getDocumentManager();
448
449 51
        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...
450
            $document = $documentManager->find($pages[$i], $locale);
451
            $documentManager->reorder($document, null);
452
        }
453 51
    }
454
455
    /**
456
     * {@inheritdoc}
457 51
     */
458 51
    public function getSecurityContext()
459 51
    {
460
        return ArticleAdmin::SECURITY_CONTEXT;
461 51
    }
462
463
    /**
464
     * Persists the document using the given information.
465 51
     *
466
     * @param array  $data
467
     * @param object $document
468
     * @param string $locale
469
     *
470
     * @throws InvalidFormException
471
     * @throws MissingParameterException
472 51
     */
473
    private function persistDocument($data, $document, $locale)
474 51
    {
475
        $form = $this->createForm(
476
            ArticleDocumentType::class,
477
            $document,
478
            [
479
                // disable csrf protection, since we can't produce a token, because the form is cached on the client
480 1
                'csrf_protection' => false,
481
            ]
482 1
        );
483
        $form->submit($data, false);
484
485
        if (!$form->isValid()) {
486
            throw new InvalidFormException($form);
487
        }
488
489
        if (array_key_exists('author', $data) && null === $data['author']) {
490
            $document->setAuthor(null);
491
        }
492 51
493
        $this->getDocumentManager()->persist(
494
            $document,
495 51
            $locale,
496 17
            [
497 17
                'user' => $this->getUser()->getId(),
498
                'clear_missing_content' => false,
499 51
            ]
500
        );
501
    }
502
503
    /**
504
     * Returns document-manager.
505
     *
506
     * @return DocumentManagerInterface
507
     */
508 1
    protected function getDocumentManager()
509
    {
510 1
        return $this->get('sulu_document_manager.document_manager');
511 1
    }
512 1
513 1
    /**
514
     * @return ContentMapperInterface
515
     */
516 1
    protected function getMapper()
517
    {
518
        return $this->get('sulu.content.mapper');
519
    }
520
521
    /**
522
     * Delegates actions by given actionParameter, which can be retrieved from the request.
523
     *
524
     * @param string $actionParameter
525
     * @param object $document
526
     * @param string $locale
527
     */
528
    private function handleActionParameter($actionParameter, $document, $locale)
529
    {
530
        switch ($actionParameter) {
531
            case 'publish':
532
                $this->getDocumentManager()->publish($document, $locale);
533
                break;
534
        }
535
    }
536
537
    /**
538
     * Converts camel case string into normalized string with underscore.
539
     *
540
     * @param string $camel
541
     *
542
     * @return string
543
     */
544
    private function uncamelize($camel)
545
    {
546
        $camel = preg_replace(
547
            '/(?!^)[[:upper:]][[:lower:]]/',
548
            '$0',
549
            preg_replace('/(?!^)[[:upper:]]+/', '_$0', $camel)
550
        );
551
552
        return strtolower($camel);
553
    }
554
}
555