Completed
Pull Request — 5.2 (#2400)
by
unknown
12:28
created

NodeAdminController::addAction()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 56
rs 8.9599
c 0
b 0
f 0
cc 2
nc 2
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Kunstmaan\NodeBundle\Controller;
4
5
use DateTime;
6
use Doctrine\Common\Collections\ArrayCollection;
7
use Doctrine\ORM\EntityManager;
8
use InvalidArgumentException;
9
use Kunstmaan\AdminBundle\Entity\BaseUser;
10
use Kunstmaan\AdminBundle\Entity\EntityInterface;
11
use Kunstmaan\AdminBundle\Entity\User;
12
use Kunstmaan\AdminBundle\FlashMessages\FlashTypes;
13
use Kunstmaan\AdminBundle\Helper\FormWidgets\FormWidget;
14
use Kunstmaan\AdminBundle\Helper\FormWidgets\Tabs\Tab;
15
use Kunstmaan\AdminBundle\Helper\FormWidgets\Tabs\TabPane;
16
use Kunstmaan\AdminBundle\Helper\Security\Acl\AclHelper;
17
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionMap;
18
use Kunstmaan\AdminBundle\Service\AclManager;
19
use Kunstmaan\AdminListBundle\AdminList\AdminList;
20
use Kunstmaan\NodeBundle\AdminList\NodeAdminListConfigurator;
21
use Kunstmaan\NodeBundle\Entity\HasNodeInterface;
22
use Kunstmaan\NodeBundle\Entity\Node;
23
use Kunstmaan\NodeBundle\Entity\NodeTranslation;
24
use Kunstmaan\NodeBundle\Entity\NodeVersion;
25
use Kunstmaan\NodeBundle\Event\AdaptFormEvent;
26
use Kunstmaan\NodeBundle\Event\CopyPageTranslationNodeEvent;
27
use Kunstmaan\NodeBundle\Event\Events;
28
use Kunstmaan\NodeBundle\Event\NodeEvent;
29
use Kunstmaan\NodeBundle\Event\RecopyPageTranslationNodeEvent;
30
use Kunstmaan\NodeBundle\Event\RevertNodeAction;
31
use Kunstmaan\NodeBundle\Form\NodeMenuTabAdminType;
32
use Kunstmaan\NodeBundle\Form\NodeMenuTabTranslationAdminType;
33
use Kunstmaan\NodeBundle\Helper\NodeAdmin\NodeAdminPublisher;
34
use Kunstmaan\NodeBundle\Helper\NodeAdmin\NodeVersionLockHelper;
35
use Kunstmaan\NodeBundle\Repository\NodeVersionRepository;
36
use Kunstmaan\UtilitiesBundle\Helper\ClassLookup;
37
use Symfony\Component\Routing\Annotation\Route;
38
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
39
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
40
use Symfony\Component\HttpFoundation\JsonResponse;
41
use Symfony\Component\HttpFoundation\RedirectResponse;
42
use Symfony\Component\HttpFoundation\Request;
43
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
44
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
45
use Symfony\Component\Translation\TranslatorInterface;
46
47
/**
48
 * NodeAdminController
49
 */
50
class NodeAdminController extends Controller
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...e\Controller\Controller has been deprecated with message: since Symfony 4.2, use {@see AbstractController} instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
51
{
52
    /**
53
     * @var EntityManager
54
     */
55
    protected $em;
56
57
    /**
58
     * @var string
59
     */
60
    protected $locale;
61
62
    /**
63
     * @var AuthorizationCheckerInterface
64
     */
65
    protected $authorizationChecker;
66
67
    /**
68
     * @var BaseUser
69
     */
70
    protected $user;
71
72
    /**
73
     * @var AclHelper
74
     */
75
    protected $aclHelper;
76
77
    /**
78
     * @var AclManager
79
     */
80
    protected $aclManager;
81
82
    /**
83
     * @var NodeAdminPublisher
84
     */
85
    protected $nodePublisher;
86
87
    /**
88
     * @var TranslatorInterface
89
     */
90
    protected $translator;
91
92
    /**
93
     * init
94
     *
95
     * @param Request $request
96
     */
97
    protected function init(Request $request)
98
    {
99
        $this->em = $this->getDoctrine()->getManager();
100
        $this->locale = $request->getLocale();
101
        $this->authorizationChecker = $this->container->get('security.authorization_checker');
102
        $this->user = $this->getUser();
103
        $this->aclHelper = $this->container->get('kunstmaan_admin.acl.helper');
104
        $this->aclManager = $this->container->get('kunstmaan_admin.acl.manager');
105
        $this->nodePublisher = $this->container->get('kunstmaan_node.admin_node.publisher');
106
        $this->translator = $this->container->get('translator');
107
    }
108
109
    /**
110
     * @Route("/", name="KunstmaanNodeBundle_nodes")
111
     * @Template("KunstmaanNodeBundle:Admin:list.html.twig")
112
     *
113
     * @param Request $request
114
     *
115
     * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,AdminList>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
116
     */
117
    public function indexAction(Request $request)
118
    {
119
        $this->init($request);
120
121
        $nodeAdminListConfigurator = new NodeAdminListConfigurator(
122
            $this->em,
123
            $this->aclHelper,
124
            $this->locale,
125
            PermissionMap::PERMISSION_VIEW,
126
            $this->authorizationChecker
127
        );
128
129
        $locale = $this->locale;
130
        $acl = $this->authorizationChecker;
131
        $itemRoute = function (EntityInterface $item) use ($locale, $acl) {
132
            if ($acl->isGranted(PermissionMap::PERMISSION_VIEW, $item->getNode())) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Kunstmaan\AdminBundle\Entity\EntityInterface as the method getNode() does only exist in the following implementations of said interface: Kunstmaan\FormBundle\Entity\FormSubmission, Kunstmaan\FormBundle\Tes...List\FakeFormSubmission, Kunstmaan\NodeBundle\Entity\NodeTranslation, Kunstmaan\NodeSearchBundle\Entity\NodeSearch.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
133
                return array(
134
                    'path' => '_slug_preview',
135
                    'params' => ['_locale' => $locale, 'url' => $item->getUrl()],
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Kunstmaan\AdminBundle\Entity\EntityInterface as the method getUrl() does only exist in the following implementations of said interface: Kunstmaan\AdminBundle\Entity\Exception, Kunstmaan\MediaBundle\Entity\Media, Kunstmaan\MenuBundle\Entity\BaseMenuItem, Kunstmaan\MenuBundle\Entity\MenuItem, Kunstmaan\NodeBundle\Entity\NodeTranslation, Kunstmaan\PagePartBundle\Entity\LinkPagePart.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
136
                );
137
            }
138
        };
139
        $nodeAdminListConfigurator->addSimpleItemAction('action.preview', $itemRoute, 'eye');
140
        $nodeAdminListConfigurator->setDomainConfiguration($this->get('kunstmaan_admin.domain_configuration'));
141
        $nodeAdminListConfigurator->setShowAddHomepage($this->getParameter('kunstmaan_node.show_add_homepage') && $this->isGranted('ROLE_SUPER_ADMIN'));
142
143
        /** @var AdminList $adminlist */
144
        $adminlist = $this->get('kunstmaan_adminlist.factory')->createList($nodeAdminListConfigurator);
145
        $adminlist->bindRequest($request);
146
147
        return array(
148
            'adminlist' => $adminlist,
149
        );
150
    }
151
152
    /**
153
     * @Route(
154
     *      "/{id}/copyfromotherlanguage",
155
     *      requirements={"id" = "\d+"},
156
     *      name="KunstmaanNodeBundle_nodes_copyfromotherlanguage",
157
     *      methods={"GET"}
158
     * )
159
     *
160
     * @param Request $request
161
     * @param int     $id      The node id
162
     *
163
     * @return RedirectResponse
164
     *
165
     * @throws AccessDeniedException
166
     */
167
    public function copyFromOtherLanguageAction(Request $request, $id)
168
    {
169
        $this->init($request);
170
        /* @var Node $node */
171
        $node = $this->em->getRepository('KunstmaanNodeBundle:Node')->find($id);
172
173
        $this->denyAccessUnlessGranted(PermissionMap::PERMISSION_EDIT, $node);
174
175
        $originalLanguage = $request->get('originallanguage');
176
        $otherLanguageNodeTranslation = $node->getNodeTranslation($originalLanguage, true);
177
        $otherLanguageNodeNodeVersion = $otherLanguageNodeTranslation->getPublicNodeVersion();
178
        $otherLanguagePage = $otherLanguageNodeNodeVersion->getRef($this->em);
179
        $myLanguagePage = $this->get('kunstmaan_admin.clone.helper')
180
            ->deepCloneAndSave($otherLanguagePage);
181
182
        /* @var NodeTranslation $nodeTranslation */
183
        $nodeTranslation = $this->em->getRepository('KunstmaanNodeBundle:NodeTranslation')
184
            ->createNodeTranslationFor($myLanguagePage, $this->locale, $node, $this->user);
185
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
186
187
        $this->get('event_dispatcher')->dispatch(
188
            Events::COPY_PAGE_TRANSLATION,
189
            new CopyPageTranslationNodeEvent(
190
                $node,
191
                $nodeTranslation,
192
                $nodeVersion,
193
                $myLanguagePage,
194
                $otherLanguageNodeTranslation,
0 ignored issues
show
Bug introduced by
It seems like $otherLanguageNodeTranslation defined by $node->getNodeTranslatio...originalLanguage, true) on line 176 can be null; however, Kunstmaan\NodeBundle\Eve...odeEvent::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
195
                $otherLanguageNodeNodeVersion,
196
                $otherLanguagePage,
197
                $originalLanguage
198
            )
199
        );
200
201
        return $this->redirect($this->generateUrl('KunstmaanNodeBundle_nodes_edit', array('id' => $id)));
202
    }
203
204
    /**
205
     * @Route(
206
     *      "/{id}/recopyfromotherlanguage",
207
     *      requirements={"id" = "\d+"},
208
     *      name="KunstmaanNodeBundle_nodes_recopyfromotherlanguage",
209
     *      methods={"POST"}
210
     * )
211
     *
212
     * @param Request $request
213
     * @param int     $id      The node id
214
     *
215
     * @return RedirectResponse
216
     *
217
     * @throws AccessDeniedException
218
     */
219
    public function recopyFromOtherLanguageAction(Request $request, $id)
220
    {
221
        $this->init($request);
222
        /* @var Node $node */
223
        $node = $this->em->getRepository('KunstmaanNodeBundle:Node')->find($id);
224
225
        $this->denyAccessUnlessGranted(PermissionMap::PERMISSION_EDIT, $node);
226
227
        $otherLanguageNodeTranslation = $this->em->getRepository('KunstmaanNodeBundle:NodeTranslation')->find($request->get('source'));
228
        $otherLanguageNodeNodeVersion = $otherLanguageNodeTranslation->getPublicNodeVersion();
229
        $otherLanguagePage = $otherLanguageNodeNodeVersion->getRef($this->em);
230
        $myLanguagePage = $this->get('kunstmaan_admin.clone.helper')
231
            ->deepCloneAndSave($otherLanguagePage);
232
233
        /* @var NodeTranslation $nodeTranslation */
234
        $nodeTranslation = $this->em->getRepository('KunstmaanNodeBundle:NodeTranslation')
235
            ->addDraftNodeVersionFor($myLanguagePage, $this->locale, $node, $this->user);
236
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
237
238
        $this->get('event_dispatcher')->dispatch(
239
            Events::RECOPY_PAGE_TRANSLATION,
240
            new RecopyPageTranslationNodeEvent(
241
                $node,
242
                $nodeTranslation,
243
                $nodeVersion,
244
                $myLanguagePage,
245
                $otherLanguageNodeTranslation,
0 ignored issues
show
Documentation introduced by
$otherLanguageNodeTranslation is of type object|null, but the function expects a object<Kunstmaan\NodeBun...Entity\NodeTranslation>.

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...
246
                $otherLanguageNodeNodeVersion,
247
                $otherLanguagePage,
248
                $otherLanguageNodeTranslation->getLang()
249
            )
250
        );
251
252
        return $this->redirect($this->generateUrl('KunstmaanNodeBundle_nodes_edit', array('id' => $id, 'subaction' => NodeVersion::DRAFT_VERSION)));
253
    }
254
255
    /**
256
     * @Route(
257
     *      "/{id}/createemptypage",
258
     *      requirements={"id" = "\d+"},
259
     *      name="KunstmaanNodeBundle_nodes_createemptypage",
260
     *      methods={"GET"}
261
     * )
262
     *
263
     * @param Request $request
264
     * @param int     $id
265
     *
266
     * @return RedirectResponse
267
     *
268
     * @throws AccessDeniedException
269
     */
270
    public function createEmptyPageAction(Request $request, $id)
271
    {
272
        $this->init($request);
273
        /* @var Node $node */
274
        $node = $this->em->getRepository('KunstmaanNodeBundle:Node')->find($id);
275
276
        $this->denyAccessUnlessGranted(PermissionMap::PERMISSION_EDIT, $node);
277
278
        $entityName = $node->getRefEntityName();
279
        /* @var HasNodeInterface $myLanguagePage */
280
        $myLanguagePage = new $entityName();
281
        $myLanguagePage->setTitle('New page');
282
283
        $this->em->persist($myLanguagePage);
284
        $this->em->flush();
285
        /* @var NodeTranslation $nodeTranslation */
286
        $nodeTranslation = $this->em->getRepository('KunstmaanNodeBundle:NodeTranslation')
287
            ->createNodeTranslationFor($myLanguagePage, $this->locale, $node, $this->user);
288
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
289
290
        $this->get('event_dispatcher')->dispatch(
291
            Events::ADD_EMPTY_PAGE_TRANSLATION,
292
            new NodeEvent($node, $nodeTranslation, $nodeVersion, $myLanguagePage)
293
        );
294
295
        return $this->redirect($this->generateUrl('KunstmaanNodeBundle_nodes_edit', array('id' => $id)));
296
    }
297
298
    /**
299
     * @Route("/{id}/publish", requirements={"id" =
300
     *                         "\d+"},
301
     *                         name="KunstmaanNodeBundle_nodes_publish", methods={"GET", "POST"})
302
     *
303
     * @param Request $request
304
     * @param int     $id
305
     *
306
     * @return RedirectResponse
307
     *
308
     * @throws AccessDeniedException
309
     */
310 View Code Duplication
    public function publishAction(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...
311
    {
312
        $this->init($request);
313
        /* @var Node $node */
314
        $node = $this->em->getRepository('KunstmaanNodeBundle:Node')->find($id);
315
316
        $nodeTranslation = $node->getNodeTranslation($this->locale, true);
317
        $request = $this->get('request_stack')->getCurrentRequest();
318
        $this->nodePublisher->chooseHowToPublish($request, $nodeTranslation, $this->translator);
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $node->getNodeTranslation($this->locale, true) on line 316 can be null; however, Kunstmaan\NodeBundle\Hel...r::chooseHowToPublish() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
319
320
        return $this->redirect($this->generateUrl('KunstmaanNodeBundle_nodes_edit', array('id' => $node->getId())));
321
    }
322
323
    /**
324
     * @Route(
325
     *      "/{id}/unpublish",
326
     *      requirements={"id" = "\d+"},
327
     *      name="KunstmaanNodeBundle_nodes_unpublish",
328
     *      methods={"GET", "POST"}
329
     * )
330
     *
331
     * @param Request $request
332
     * @param int     $id
333
     *
334
     * @return RedirectResponse
335
     *
336
     * @throws AccessDeniedException
337
     */
338 View Code Duplication
    public function unPublishAction(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...
339
    {
340
        $this->init($request);
341
        /* @var Node $node */
342
        $node = $this->em->getRepository('KunstmaanNodeBundle:Node')->find($id);
343
344
        $nodeTranslation = $node->getNodeTranslation($this->locale, true);
345
        $request = $this->get('request_stack')->getCurrentRequest();
346
        $this->nodePublisher->chooseHowToUnpublish($request, $nodeTranslation, $this->translator);
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $node->getNodeTranslation($this->locale, true) on line 344 can be null; however, Kunstmaan\NodeBundle\Hel...:chooseHowToUnpublish() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
347
348
        return $this->redirect($this->generateUrl('KunstmaanNodeBundle_nodes_edit', array('id' => $node->getId())));
349
    }
350
351
    /**
352
     * @Route(
353
     *      "/{id}/unschedulepublish",
354
     *      requirements={"id" = "\d+"},
355
     *      name="KunstmaanNodeBundle_nodes_unschedule_publish",
356
     *      methods={"GET", "POST"}
357
     * )
358
     *
359
     * @param Request $request
360
     * @param int     $id
361
     *
362
     * @return RedirectResponse
363
     *
364
     * @throws AccessDeniedException
365
     */
366 View Code Duplication
    public function unSchedulePublishAction(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...
367
    {
368
        $this->init($request);
369
370
        /* @var Node $node */
371
        $node = $this->em->getRepository('KunstmaanNodeBundle:Node')->find($id);
372
373
        $nodeTranslation = $node->getNodeTranslation($this->locale, true);
374
        $this->nodePublisher->unSchedulePublish($nodeTranslation);
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $node->getNodeTranslation($this->locale, true) on line 373 can be null; however, Kunstmaan\NodeBundle\Hel...er::unSchedulePublish() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
375
376
        $this->addFlash(
377
            FlashTypes::SUCCESS,
378
            $this->get('translator')->trans('kuma_node.admin.unschedule.flash.success')
379
        );
380
381
        return $this->redirect($this->generateUrl('KunstmaanNodeBundle_nodes_edit', array('id' => $id)));
382
    }
383
384
    /**
385
     * @Route(
386
     *      "/{id}/delete",
387
     *      requirements={"id" = "\d+"},
388
     *      name="KunstmaanNodeBundle_nodes_delete",
389
     *      methods={"POST"}
390
     * )
391
     *
392
     * @param Request $request
393
     * @param int     $id
394
     *
395
     * @return RedirectResponse
396
     *
397
     * @throws AccessDeniedException
398
     */
399
    public function deleteAction(Request $request, $id)
400
    {
401
        $this->init($request);
402
        /* @var Node $node */
403
        $node = $this->em->getRepository('KunstmaanNodeBundle:Node')->find($id);
404
405
        $this->denyAccessUnlessGranted(PermissionMap::PERMISSION_DELETE, $node);
406
407
        $nodeTranslation = $node->getNodeTranslation($this->locale, true);
408
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
409
        $page = $nodeVersion->getRef($this->em);
410
411
        $this->get('event_dispatcher')->dispatch(
412
            Events::PRE_DELETE,
413
            new NodeEvent($node, $nodeTranslation, $nodeVersion, $page)
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $node->getNodeTranslation($this->locale, true) on line 407 can be null; however, Kunstmaan\NodeBundle\Eve...odeEvent::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
414
        );
415
416
        $node->setDeleted(true);
417
        $this->em->persist($node);
418
419
        $children = $node->getChildren();
420
        $this->deleteNodeChildren($this->em, $this->user, $this->locale, $children);
421
        $this->em->flush();
422
423
        $event = new NodeEvent($node, $nodeTranslation, $nodeVersion, $page);
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $node->getNodeTranslation($this->locale, true) on line 407 can be null; however, Kunstmaan\NodeBundle\Eve...odeEvent::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
424
        $this->get('event_dispatcher')->dispatch(Events::POST_DELETE, $event);
425
        if (null === $response = $event->getResponse()) {
426
            $nodeParent = $node->getParent();
427
            // Check if we have a parent. Otherwise redirect to pages overview.
428
            if ($nodeParent) {
429
                $url = $this->get('router')->generate(
430
                    'KunstmaanNodeBundle_nodes_edit',
431
                    array('id' => $nodeParent->getId())
432
                );
433
            } else {
434
                $url = $this->get('router')->generate(
435
                    'KunstmaanNodeBundle_nodes'
436
                );
437
            }
438
            $response = new RedirectResponse($url);
439
        }
440
441
        $this->addFlash(
442
            FlashTypes::SUCCESS,
443
            $this->get('translator')->trans('kuma_node.admin.delete.flash.success')
444
        );
445
446
        return $response;
447
    }
448
449
    /**
450
     * @Route(
451
     *      "/{id}/duplicate",
452
     *      requirements={"id" = "\d+"},
453
     *      name="KunstmaanNodeBundle_nodes_duplicate",
454
     *      methods={"POST"}
455
     * )
456
     *
457
     * @param Request $request
458
     * @param int     $id
459
     *
460
     * @return RedirectResponse
461
     *
462
     * @throws AccessDeniedException
463
     */
464
    public function duplicateAction(Request $request, $id)
465
    {
466
        $this->init($request);
467
        /* @var Node $parentNode */
468
        $originalNode = $this->em->getRepository('KunstmaanNodeBundle:Node')
469
            ->find($id);
470
471
        // Check with Acl
472
        $this->denyAccessUnlessGranted(PermissionMap::PERMISSION_EDIT, $originalNode);
473
474
        $request = $this->get('request_stack')->getCurrentRequest();
475
476
        $originalNodeTranslations = $originalNode->getNodeTranslation($this->locale, true);
477
        $originalRef = $originalNodeTranslations->getPublicNodeVersion()->getRef($this->em);
478
        $newPage = $this->get('kunstmaan_admin.clone.helper')
479
            ->deepCloneAndSave($originalRef);
480
481
        //set the title
482
        $title = $request->get('title');
483
        if (is_string($title) && !empty($title)) {
484
            $newPage->setTitle($title);
485
        } else {
486
            $newPage->setTitle('New page');
487
        }
488
489
        //set the parent
490
        $parentNodeTranslation = $originalNode->getParent()->getNodeTranslation($this->locale, true);
491
        $parent = $parentNodeTranslation->getPublicNodeVersion()->getRef($this->em);
492
        $newPage->setParent($parent);
493
        $this->em->persist($newPage);
494
        $this->em->flush();
495
496
        /* @var Node $nodeNewPage */
497
        $nodeNewPage = $this->em->getRepository('KunstmaanNodeBundle:Node')->createNodeFor(
498
            $newPage,
499
            $this->locale,
500
            $this->user
501
        );
502
503
        $nodeTranslation = $nodeNewPage->getNodeTranslation($this->locale, true);
504
        if ($newPage->isStructurePage()) {
505
            $nodeTranslation->setSlug('');
506
            $this->em->persist($nodeTranslation);
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $nodeNewPage->getNodeTra...on($this->locale, true) on line 503 can be null; however, Doctrine\ORM\EntityManager::persist() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
507
        }
508
        $this->em->flush();
509
510
        $this->aclManager->updateNodeAcl($originalNode, $nodeNewPage);
0 ignored issues
show
Documentation introduced by
$originalNode is of type object|null, but the function expects a object<Kunstmaan\NodeBundle\Entity\Node>.

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...
511
512
        $this->addFlash(
513
            FlashTypes::SUCCESS,
514
            $this->get('translator')->trans('kuma_node.admin.duplicate.flash.success')
515
        );
516
517
        return $this->redirect(
518
            $this->generateUrl('KunstmaanNodeBundle_nodes_edit', array('id' => $nodeNewPage->getId()))
519
        );
520
    }
521
522
    /**
523
     * @Route(
524
     *      "/{id}/revert",
525
     *      requirements={"id" = "\d+"},
526
     *      defaults={"subaction" = "public"},
527
     *      name="KunstmaanNodeBundle_nodes_revert",
528
     *      methods={"GET"}
529
     * )
530
     *
531
     * @param Request $request
532
     * @param int     $id      The node id
533
     *
534
     * @return RedirectResponse
535
     *
536
     * @throws AccessDeniedException
537
     * @throws InvalidArgumentException
538
     */
539
    public function revertAction(Request $request, $id)
540
    {
541
        $this->init($request);
542
        /* @var Node $node */
543
        $node = $this->em->getRepository('KunstmaanNodeBundle:Node')->find($id);
544
545
        $this->denyAccessUnlessGranted(PermissionMap::PERMISSION_EDIT, $node);
546
547
        $version = $request->get('version');
548
549
        if (empty($version) || !is_numeric($version)) {
550
            throw new InvalidArgumentException('No version was specified');
551
        }
552
553
        /* @var NodeVersionRepository $nodeVersionRepo */
554
        $nodeVersionRepo = $this->em->getRepository('KunstmaanNodeBundle:NodeVersion');
555
        /* @var NodeVersion $nodeVersion */
556
        $nodeVersion = $nodeVersionRepo->find($version);
557
558
        if (is_null($nodeVersion)) {
559
            throw new InvalidArgumentException('Version does not exist');
560
        }
561
562
        /* @var NodeTranslation $nodeTranslation */
563
        $nodeTranslation = $node->getNodeTranslation($this->locale, true);
564
        $page = $nodeVersion->getRef($this->em);
565
        /* @var HasNodeInterface $clonedPage */
566
        $clonedPage = $this->get('kunstmaan_admin.clone.helper')
567
            ->deepCloneAndSave($page);
568
        $newNodeVersion = $nodeVersionRepo->createNodeVersionFor(
569
            $clonedPage,
570
            $nodeTranslation,
571
            $this->user,
572
            $nodeVersion,
573
            'draft'
574
        );
575
576
        $nodeTranslation->setTitle($clonedPage->getTitle());
577
        $this->em->persist($nodeTranslation);
578
        $this->em->flush();
579
580
        $this->get('event_dispatcher')->dispatch(
581
            Events::REVERT,
582
            new RevertNodeAction(
583
                $node,
584
                $nodeTranslation,
585
                $newNodeVersion,
586
                $clonedPage,
587
                $nodeVersion,
588
                $page
0 ignored issues
show
Bug introduced by
It seems like $page defined by $nodeVersion->getRef($this->em) on line 564 can be null; however, Kunstmaan\NodeBundle\Eve...deAction::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
589
            )
590
        );
591
592
        $this->addFlash(
593
            FlashTypes::SUCCESS,
594
            $this->get('translator')->trans('kuma_node.admin.revert.flash.success')
595
        );
596
597
        return $this->redirect(
598
            $this->generateUrl(
599
                'KunstmaanNodeBundle_nodes_edit',
600
                array(
601
                    'id' => $id,
602
                    'subaction' => 'draft',
603
                )
604
            )
605
        );
606
    }
607
608
    /**
609
     * @Route(
610
     *      "/{id}/add",
611
     *      requirements={"id" = "\d+"},
612
     *      name="KunstmaanNodeBundle_nodes_add",
613
     *      methods={"POST"}
614
     * )
615
     *
616
     * @param Request $request
617
     * @param int     $id
618
     *
619
     * @return RedirectResponse
620
     *
621
     * @throws AccessDeniedException
622
     * @throws InvalidArgumentException
623
     */
624
    public function addAction(Request $request, $id)
625
    {
626
        $this->init($request);
627
        /* @var Node $parentNode */
628
        $parentNode = $this->em->getRepository('KunstmaanNodeBundle:Node')->find($id);
629
630
        // Check with Acl
631
        $this->denyAccessUnlessGranted(PermissionMap::PERMISSION_EDIT, $parentNode);
632
633
        $parentNodeTranslation = $parentNode->getNodeTranslation($this->locale, true);
634
        $parentNodeVersion = $parentNodeTranslation->getPublicNodeVersion();
635
        $parentPage = $parentNodeVersion->getRef($this->em);
636
637
        $type = $this->validatePageType($request);
638
        $newPage = $this->createNewPage($request, $type);
639
        $newPage->setParent($parentPage);
640
641
        /* @var Node $nodeNewPage */
642
        $nodeNewPage = $this->em->getRepository('KunstmaanNodeBundle:Node')
643
            ->createNodeFor($newPage, $this->locale, $this->user);
644
        $nodeTranslation = $nodeNewPage->getNodeTranslation(
645
            $this->locale,
646
            true
647
        );
648
        $weight = $this->em->getRepository('KunstmaanNodeBundle:NodeTranslation')
649
                ->getMaxChildrenWeight($parentNode, $this->locale) + 1;
650
        $nodeTranslation->setWeight($weight);
651
652
        if ($newPage->isStructurePage()) {
653
            $nodeTranslation->setSlug('');
654
        }
655
656
        $this->em->persist($nodeTranslation);
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $nodeNewPage->getNodeTra...on($this->locale, true) on line 644 can be null; however, Doctrine\ORM\EntityManager::persist() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
657
        $this->em->flush();
658
659
        $this->aclManager->updateNodeAcl($parentNode, $nodeNewPage);
660
661
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
662
663
        $this->get('event_dispatcher')->dispatch(
664
            Events::ADD_NODE,
665
            new NodeEvent(
666
                $nodeNewPage,
667
                $nodeTranslation,
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $nodeNewPage->getNodeTra...on($this->locale, true) on line 644 can be null; however, Kunstmaan\NodeBundle\Eve...odeEvent::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
668
                $nodeVersion,
669
                $newPage
670
            )
671
        );
672
673
        return $this->redirect(
674
            $this->generateUrl(
675
                'KunstmaanNodeBundle_nodes_edit',
676
                array('id' => $nodeNewPage->getId())
677
            )
678
        );
679
    }
680
681
    /**
682
     * @Route("/add-homepage", name="KunstmaanNodeBundle_nodes_add_homepage", methods={"POST"})
683
     *
684
     * @return RedirectResponse
685
     *
686
     * @throws AccessDeniedException
687
     * @throws InvalidArgumentException
688
     */
689
    public function addHomepageAction(Request $request)
690
    {
691
        $this->init($request);
692
693
        // Check with Acl
694
        $this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
695
696
        $type = $this->validatePageType($request);
697
698
        $newPage = $this->createNewPage($request, $type);
699
700
        /* @var Node $nodeNewPage */
701
        $nodeNewPage = $this->em->getRepository('KunstmaanNodeBundle:Node')
702
            ->createNodeFor($newPage, $this->locale, $this->user);
703
        $nodeTranslation = $nodeNewPage->getNodeTranslation(
704
            $this->locale,
705
            true
706
        );
707
        $this->em->flush();
708
709
        // Set default permissions
710
        $this->container->get('kunstmaan_node.acl_permission_creator_service')
711
            ->createPermission($nodeNewPage);
712
713
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
714
715
        $this->get('event_dispatcher')->dispatch(
716
            Events::ADD_NODE,
717
            new NodeEvent(
718
                $nodeNewPage,
719
                $nodeTranslation,
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $nodeNewPage->getNodeTra...on($this->locale, true) on line 703 can be null; however, Kunstmaan\NodeBundle\Eve...odeEvent::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
720
                $nodeVersion,
721
                $newPage
722
            )
723
        );
724
725
        return $this->redirect(
726
            $this->generateUrl(
727
                'KunstmaanNodeBundle_nodes_edit',
728
                array('id' => $nodeNewPage->getId())
729
            )
730
        );
731
    }
732
733
    /**
734
     * @Route("/reorder", name="KunstmaanNodeBundle_nodes_reorder", methods={"POST"})
735
     *
736
     * @param Request $request
737
     *
738
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be JsonResponse?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
739
     *
740
     * @throws AccessDeniedException
741
     */
742
    public function reorderAction(Request $request)
743
    {
744
        $this->init($request);
745
        $nodes = array();
746
        $nodeIds = $request->get('nodes');
747
        $changeParents = $request->get('parent');
748
749
        foreach ($nodeIds as $id) {
750
            /* @var Node $node */
751
            $node = $this->em->getRepository('KunstmaanNodeBundle:Node')->find($id);
752
            $this->denyAccessUnlessGranted(PermissionMap::PERMISSION_EDIT, $node);
753
            $nodes[] = $node;
754
        }
755
756
        $weight = 1;
757
        foreach ($nodes as $node) {
758
            $newParentId = isset($changeParents[$node->getId()]) ? $changeParents[$node->getId()] : null;
759
            if ($newParentId) {
760
                $parent = $this->em->getRepository('KunstmaanNodeBundle:Node')->find($newParentId);
761
                $this->denyAccessUnlessGranted(PermissionMap::PERMISSION_EDIT, $parent);
762
                $node->setParent($parent);
763
                $this->em->persist($node);
764
                $this->em->flush($node);
765
            }
766
767
            /* @var NodeTranslation $nodeTranslation */
768
            $nodeTranslation = $node->getNodeTranslation($this->locale, true);
769
770
            if ($nodeTranslation) {
771
                $nodeVersion = $nodeTranslation->getPublicNodeVersion();
772
                $page = $nodeVersion->getRef($this->em);
773
774
                $this->get('event_dispatcher')->dispatch(
775
                    Events::PRE_PERSIST,
776
                    new NodeEvent($node, $nodeTranslation, $nodeVersion, $page)
0 ignored issues
show
Bug introduced by
It seems like $page defined by $nodeVersion->getRef($this->em) on line 772 can be null; however, Kunstmaan\NodeBundle\Eve...odeEvent::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
777
                );
778
779
                $nodeTranslation->setWeight($weight);
780
                $this->em->persist($nodeTranslation);
781
                $this->em->flush($nodeTranslation);
782
783
                $this->get('event_dispatcher')->dispatch(
784
                    Events::POST_PERSIST,
785
                    new NodeEvent($node, $nodeTranslation, $nodeVersion, $page)
0 ignored issues
show
Bug introduced by
It seems like $page defined by $nodeVersion->getRef($this->em) on line 772 can be null; however, Kunstmaan\NodeBundle\Eve...odeEvent::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
786
                );
787
788
                ++$weight;
789
            }
790
        }
791
792
        return new JsonResponse(
793
            array(
794
                'Success' => 'The node-translations for [' . $this->locale . '] have got new weight values',
795
            )
796
        );
797
    }
798
799
    /**
800
     * @Route(
801
     *      "/{id}/{subaction}",
802
     *      requirements={"id" = "\d+"},
803
     *      defaults={"subaction" = "public"},
804
     *      name="KunstmaanNodeBundle_nodes_edit",
805
     *      methods={"GET", "POST"}
806
     * )
807
     * @Template("@KunstmaanNode/NodeAdmin/edit.html.twig")
808
     *
809
     * @param Request $request
810
     * @param int     $id        The node id
811
     * @param string  $subaction The subaction (draft|public)
812
     *
813
     * @return RedirectResponse|array
0 ignored issues
show
Documentation introduced by
Should the return type not be \Symfony\Component\HttpFoundation\Response|array?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
814
     *
815
     * @throws AccessDeniedException
816
     */
817
    public function editAction(Request $request, $id, $subaction)
818
    {
819
        $this->init($request);
820
        /* @var Node $node */
821
        $node = $this->em->getRepository('KunstmaanNodeBundle:Node')->find($id);
822
823
        $this->denyAccessUnlessGranted(PermissionMap::PERMISSION_EDIT, $node);
824
825
        $tabPane = new TabPane(
826
            'todo',
827
            $request,
828
            $this->container->get('form.factory')
829
        );
830
831
        $nodeTranslation = $node->getNodeTranslation($this->locale, true);
832
        if (!$nodeTranslation) {
833
            return $this->renderNodeNotTranslatedPage($node);
834
        }
835
836
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
837
        $draftNodeVersion = $nodeTranslation->getDraftNodeVersion();
838
        $nodeVersionIsLocked = false;
839
840
        /* @var HasNodeInterface $page */
841
        $page = null;
0 ignored issues
show
Unused Code introduced by
$page is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
842
        $draft = ($subaction == 'draft');
843
        $saveAsDraft = $request->get('saveasdraft');
844
        if ((!$draft && !empty($saveAsDraft)) || ($draft && is_null($draftNodeVersion))) {
845
            // Create a new draft version
846
            $draft = true;
847
            $subaction = 'draft';
848
            $page = $nodeVersion->getRef($this->em);
849
            $nodeVersion = $this->createDraftVersion(
850
                $page,
0 ignored issues
show
Bug introduced by
It seems like $page defined by $nodeVersion->getRef($this->em) on line 848 can be null; however, Kunstmaan\NodeBundle\Con...r::createDraftVersion() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
851
                $nodeTranslation,
852
                $nodeVersion
853
            );
854
            $draftNodeVersion = $nodeVersion;
855
        } elseif ($draft) {
856
            $nodeVersion = $draftNodeVersion;
857
            $page = $nodeVersion->getRef($this->em);
858
        } else {
859
            if ($request->getMethod() == 'POST') {
860
                $nodeVersionIsLocked = $this->isNodeVersionLocked($nodeTranslation, true);
861
862
                //Check the version timeout and make a new nodeversion if the timeout is passed
863
                $thresholdDate = date(
864
                    'Y-m-d H:i:s',
865
                    time() - $this->getParameter(
866
                        'kunstmaan_node.version_timeout'
867
                    )
868
                );
869
                $updatedDate = date(
870
                    'Y-m-d H:i:s',
871
                    strtotime($nodeVersion->getUpdated()->format('Y-m-d H:i:s'))
872
                );
873 View Code Duplication
                if ($thresholdDate >= $updatedDate || $nodeVersionIsLocked) {
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...
874
                    $page = $nodeVersion->getRef($this->em);
875
                    if ($nodeVersion == $nodeTranslation->getPublicNodeVersion()) {
876
                        $this->nodePublisher
877
                            ->createPublicVersion(
878
                                $page,
0 ignored issues
show
Bug introduced by
It seems like $page defined by $nodeVersion->getRef($this->em) on line 874 can be null; however, Kunstmaan\NodeBundle\Hel...::createPublicVersion() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
879
                                $nodeTranslation,
880
                                $nodeVersion,
881
                                $this->user
882
                            );
883
                    } else {
884
                        $this->createDraftVersion(
885
                            $page,
0 ignored issues
show
Bug introduced by
It seems like $page defined by $nodeVersion->getRef($this->em) on line 874 can be null; however, Kunstmaan\NodeBundle\Con...r::createDraftVersion() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
886
                            $nodeTranslation,
887
                            $nodeVersion
888
                        );
889
                    }
890
                }
891
            }
892
            $page = $nodeVersion->getRef($this->em);
893
        }
894
        $isStructurePage = $page->isStructurePage();
895
896
        $menubuilder = $this->get('kunstmaan_node.actions_menu_builder');
897
        $menubuilder->setActiveNodeVersion($nodeVersion);
898
        $menubuilder->setEditableNode(!$isStructurePage);
899
900
        // Building the form
901
        $propertiesWidget = new FormWidget();
902
        $propertiesWidget->addType('main', $page->getDefaultAdminType(), $page);
903
        $propertiesWidget->addType('node', $node->getDefaultAdminType(), $node);
904
        $tabPane->addTab(new Tab('kuma_node.tab.properties.title', $propertiesWidget));
905
906
        // Menu tab
907
        $menuWidget = new FormWidget();
908
        $menuWidget->addType(
909
            'menunodetranslation',
910
            NodeMenuTabTranslationAdminType::class,
911
            $nodeTranslation,
912
            ['slugable' => !$isStructurePage]
913
        );
914
        $menuWidget->addType('menunode', NodeMenuTabAdminType::class, $node, ['available_in_nav' => !$isStructurePage]);
915
        $tabPane->addTab(new Tab('kuma_node.tab.menu.title', $menuWidget));
916
917
        $this->get('event_dispatcher')->dispatch(
918
            Events::ADAPT_FORM,
919
            new AdaptFormEvent(
920
                $request,
921
                $tabPane,
922
                $page,
923
                $node,
924
                $nodeTranslation,
925
                $nodeVersion
926
            )
927
        );
928
929
        $tabPane->buildForm();
930
931
        if ($request->getMethod() == 'POST') {
932
            $tabPane->bindRequest($request);
933
934
            // Don't redirect to listing when coming from ajax request, needed for url chooser.
935
            if ($tabPane->isValid() && !$request->isXmlHttpRequest()) {
936
                $this->get('event_dispatcher')->dispatch(
937
                    Events::PRE_PERSIST,
938
                    new NodeEvent($node, $nodeTranslation, $nodeVersion, $page)
0 ignored issues
show
Bug introduced by
It seems like $nodeVersion defined by $draftNodeVersion on line 856 can be null; however, Kunstmaan\NodeBundle\Eve...odeEvent::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
939
                );
940
941
                $nodeTranslation->setTitle($page->getTitle());
942
                if ($isStructurePage) {
943
                    $nodeTranslation->setSlug('');
944
                }
945
                $nodeVersion->setUpdated(new DateTime());
946
                if ($nodeVersion->getType() == 'public') {
947
                    $nodeTranslation->setUpdated($nodeVersion->getUpdated());
948
                }
949
                $this->em->persist($nodeTranslation);
950
                $this->em->persist($nodeVersion);
0 ignored issues
show
Bug introduced by
It seems like $nodeVersion defined by $draftNodeVersion on line 856 can be null; however, Doctrine\ORM\EntityManager::persist() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
951
                $tabPane->persist($this->em);
952
                $this->em->flush();
953
954
                $this->get('event_dispatcher')->dispatch(
955
                    Events::POST_PERSIST,
956
                    new NodeEvent($node, $nodeTranslation, $nodeVersion, $page)
0 ignored issues
show
Bug introduced by
It seems like $nodeVersion defined by $draftNodeVersion on line 856 can be null; however, Kunstmaan\NodeBundle\Eve...odeEvent::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
957
                );
958
959
                if ($nodeVersionIsLocked) {
960
                    $this->addFlash(
961
                        FlashTypes::SUCCESS,
962
                        $this->get('translator')->trans('kuma_node.admin.edit.flash.locked_success')
963
                    );
964
                } else {
965
                    if ($request->request->has('publishing') || $request->request->has('publish_later')) {
966
                        $this->nodePublisher->chooseHowToPublish($request, $nodeTranslation, $this->translator);
967
                    } elseif ($request->request->has('unpublishing') || $request->request->has('unpublish_later')) {
968
                        $this->nodePublisher->chooseHowToUnpublish($request, $nodeTranslation, $this->translator);
969
                    } else {
970
                        $this->addFlash(
971
                            FlashTypes::SUCCESS,
972
                            $this->get('translator')->trans('kuma_node.admin.edit.flash.success')
973
                        );
974
                    }
975
                }
976
977
                $params = [
978
                    'id' => $node->getId(),
979
                    'subaction' => $subaction,
980
                    'currenttab' => $tabPane->getActiveTab(),
981
                ];
982
                $params = array_merge(
983
                    $params,
984
                    $tabPane->getExtraParams($request)
985
                );
986
987
                return $this->redirect(
988
                    $this->generateUrl(
989
                        'KunstmaanNodeBundle_nodes_edit',
990
                        $params
991
                    )
992
                );
993
            }
994
        }
995
996
        $nodeVersions = $this->em->getRepository(
997
            'KunstmaanNodeBundle:NodeVersion'
998
        )->findBy(
999
            ['nodeTranslation' => $nodeTranslation],
1000
            ['updated' => 'ASC']
1001
        );
1002
        $queuedNodeTranslationAction = $this->em->getRepository(
1003
            'KunstmaanNodeBundle:QueuedNodeTranslationAction'
1004
        )->findOneBy(['nodeTranslation' => $nodeTranslation]);
1005
1006
        return [
1007
            'page' => $page,
1008
            'entityname' => ClassLookup::getClass($page),
1009
            'nodeVersions' => $nodeVersions,
1010
            'node' => $node,
1011
            'nodeTranslation' => $nodeTranslation,
1012
            'draft' => $draft,
1013
            'draftNodeVersion' => $draftNodeVersion,
1014
            'nodeVersion' => $nodeVersion,
1015
            'subaction' => $subaction,
1016
            'tabPane' => $tabPane,
1017
            'editmode' => true,
1018
            'queuedNodeTranslationAction' => $queuedNodeTranslationAction,
1019
            'nodeVersionLockCheck' => $this->container->getParameter('kunstmaan_node.lock_enabled'),
1020
            'nodeVersionLockInterval' => $this->container->getParameter('kunstmaan_node.lock_check_interval'),
1021
        ];
1022
    }
1023
1024
    /**
1025
     * @Route(
1026
     *      "checkNodeVersionLock/{id}/{public}",
1027
     *      requirements={"id" = "\d+", "public" = "(0|1)"},
1028
     *      name="KunstmaanNodeBundle_nodes_versionlock_check"
1029
     * )
1030
     *
1031
     * @param Request $request
1032
     * @param $id
1033
     *
1034
     * @return JsonResponse
1035
     */
1036
    public function checkNodeVersionLockAction(Request $request, $id, $public)
1037
    {
1038
        $nodeVersionIsLocked = false;
1039
        $message = '';
1040
        $this->init($request);
1041
1042
        /* @var Node $node */
1043
        $node = $this->em->getRepository('KunstmaanNodeBundle:Node')->find($id);
1044
1045
        try {
1046
            $this->checkPermission($node, PermissionMap::PERMISSION_EDIT);
1047
1048
            /** @var NodeVersionLockHelper $nodeVersionLockHelper */
1049
            $nodeVersionLockHelper = $this->get('kunstmaan_node.admin_node.node_version_lock_helper');
1050
            $nodeTranslation = $node->getNodeTranslation($this->locale, true);
1051
1052
            if ($nodeTranslation) {
1053
                $nodeVersionIsLocked = $nodeVersionLockHelper->isNodeVersionLocked($this->getUser(), $nodeTranslation, $public);
0 ignored issues
show
Documentation introduced by
$this->getUser() is of type null|object, but the function expects a object<Kunstmaan\AdminBundle\Entity\BaseUser>.

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...
1054
1055
                if ($nodeVersionIsLocked) {
1056
                    $users = $nodeVersionLockHelper->getUsersWithNodeVersionLock($nodeTranslation, $public, $this->getUser());
1057
                    $message = $this->get('translator')->trans('kuma_node.admin.edit.flash.locked', array('%users%' => implode(', ', $users)));
1058
                }
1059
            }
1060
        } catch (AccessDeniedException $ade) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
1061
        }
1062
1063
        return new JsonResponse(['lock' => $nodeVersionIsLocked, 'message' => $message]);
1064
    }
1065
1066
    /**
1067
     * @param NodeTranslation $nodeTranslation
1068
     * @param bool            $isPublic
1069
     *
1070
     * @return bool
1071
     */
1072
    private function isNodeVersionLocked(NodeTranslation $nodeTranslation, $isPublic)
1073
    {
1074
        if ($this->container->getParameter('kunstmaan_node.lock_enabled')) {
1075
            /** @var NodeVersionLockHelper $nodeVersionLockHelper */
1076
            $nodeVersionLockHelper = $this->get('kunstmaan_node.admin_node.node_version_lock_helper');
1077
            $nodeVersionIsLocked = $nodeVersionLockHelper->isNodeVersionLocked($this->getUser(), $nodeTranslation, $isPublic);
0 ignored issues
show
Documentation introduced by
$this->getUser() is of type null|object, but the function expects a object<Kunstmaan\AdminBundle\Entity\BaseUser>.

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...
1078
1079
            return $nodeVersionIsLocked;
1080
        }
1081
1082
        return false;
1083
    }
1084
1085
    /**
1086
     * @param HasNodeInterface $page            The page
1087
     * @param NodeTranslation  $nodeTranslation The node translation
1088
     * @param NodeVersion      $nodeVersion     The node version
1089
     *
1090
     * @return NodeVersion
1091
     */
1092
    private function createDraftVersion(
1093
        HasNodeInterface $page,
1094
        NodeTranslation $nodeTranslation,
1095
        NodeVersion $nodeVersion
1096
    ) {
1097
        $publicPage = $this->get('kunstmaan_admin.clone.helper')
1098
            ->deepCloneAndSave($page);
1099
        /* @var NodeVersion $publicNodeVersion */
1100
1101
        $publicNodeVersion = $this->em->getRepository(
1102
            'KunstmaanNodeBundle:NodeVersion'
1103
        )->createNodeVersionFor(
1104
            $publicPage,
1105
            $nodeTranslation,
1106
            $this->user,
1107
            $nodeVersion->getOrigin(),
1108
            'public',
1109
            $nodeVersion->getCreated()
1110
        );
1111
1112
        $nodeTranslation->setPublicNodeVersion($publicNodeVersion);
1113
        $nodeVersion->setType('draft');
1114
        $nodeVersion->setOrigin($publicNodeVersion);
1115
        $nodeVersion->setCreated(new DateTime());
1116
1117
        $this->em->persist($nodeTranslation);
1118
        $this->em->persist($nodeVersion);
1119
        $this->em->flush();
1120
1121
        $this->get('event_dispatcher')->dispatch(
1122
            Events::CREATE_DRAFT_VERSION,
1123
            new NodeEvent(
1124
                $nodeTranslation->getNode(),
1125
                $nodeTranslation,
1126
                $nodeVersion,
1127
                $page
1128
            )
1129
        );
1130
1131
        return $nodeVersion;
1132
    }
1133
1134
    /**
1135
     * @param Node   $node       The node
1136
     * @param string $permission The permission to check for
1137
     *
1138
     * @throws AccessDeniedException
1139
     */
1140
    private function checkPermission(Node $node, $permission)
1141
    {
1142
        if (false === $this->authorizationChecker->isGranted($permission, $node)) {
1143
            throw new AccessDeniedException();
1144
        }
1145
    }
1146
1147
    /**
1148
     * @param EntityManager   $em       The Entity Manager
1149
     * @param BaseUser        $user     The user who deletes the children
1150
     * @param string          $locale   The locale that was used
1151
     * @param ArrayCollection $children The children array
1152
     */
1153
    private function deleteNodeChildren(
1154
        EntityManager $em,
1155
        BaseUser $user,
1156
        $locale,
1157
        ArrayCollection $children
1158
    ) {
1159
        /* @var Node $childNode */
1160
        foreach ($children as $childNode) {
1161
            $childNodeTranslation = $childNode->getNodeTranslation(
1162
                $this->locale,
1163
                true
1164
            );
1165
1166
            $childNodeVersion = $childNodeTranslation->getPublicNodeVersion();
1167
            $childNodePage = $childNodeVersion->getRef($this->em);
1168
1169
            $this->get('event_dispatcher')->dispatch(
1170
                Events::PRE_DELETE,
1171
                new NodeEvent(
1172
                    $childNode,
1173
                    $childNodeTranslation,
1174
                    $childNodeVersion,
1175
                    $childNodePage
1176
                )
1177
            );
1178
1179
            $childNode->setDeleted(true);
1180
            $this->em->persist($childNode);
1181
1182
            $children2 = $childNode->getChildren();
1183
            $this->deleteNodeChildren($em, $user, $locale, $children2);
1184
1185
            $this->get('event_dispatcher')->dispatch(
1186
                Events::POST_DELETE,
1187
                new NodeEvent(
1188
                    $childNode,
1189
                    $childNodeTranslation,
1190
                    $childNodeVersion,
1191
                    $childNodePage
1192
                )
1193
            );
1194
        }
1195
    }
1196
1197
    /**
1198
     * @param Request $request
1199
     * @param string  $type
1200
     *
1201
     * @return HasNodeInterface
1202
     */
1203
    private function createNewPage(Request $request, $type)
1204
    {
1205
        /* @var HasNodeInterface $newPage */
1206
        $newPage = new $type();
1207
1208
        $title = $request->get('title');
1209
        if (is_string($title) && !empty($title)) {
1210
            $newPage->setTitle($title);
1211
        } else {
1212
            $newPage->setTitle($this->get('translator')->trans('kuma_node.admin.new_page.title.default'));
1213
        }
1214
        $this->em->persist($newPage);
1215
        $this->em->flush();
1216
1217
        return $newPage;
1218
    }
1219
1220
    /**
1221
     * @param Request $request
1222
     *
1223
     * @return string
1224
     * @throw InvalidArgumentException
1225
     */
1226
    private function validatePageType($request)
1227
    {
1228
        $type = $request->get('type');
1229
1230
        if (empty($type)) {
1231
            throw new InvalidArgumentException(
1232
                'Please specify a type of page you want to create'
1233
            );
1234
        }
1235
1236
        return $type;
1237
    }
1238
1239
    /**
1240
     * @param Node $node
1241
     *
1242
     * @return \Symfony\Component\HttpFoundation\Response
1243
     */
1244
    private function renderNodeNotTranslatedPage(Node $node)
1245
    {
1246
        //try to find a parent node with the correct translation, if there is none allow copy.
1247
        //if there is a parent but it doesn't have the language to copy to don't allow it
1248
        $parentNode = $node->getParent();
1249
        if ($parentNode) {
1250
            $parentNodeTranslation = $parentNode->getNodeTranslation(
1251
                $this->locale,
1252
                true
1253
            );
1254
            $parentsAreOk = false;
1255
1256
            if ($parentNodeTranslation) {
1257
                $parentsAreOk = $this->em->getRepository(
1258
                    'KunstmaanNodeBundle:NodeTranslation'
1259
                )->hasParentNodeTranslationsForLanguage(
1260
                    $node->getParent()->getNodeTranslation(
1261
                        $this->locale,
1262
                        true
1263
                    ),
1264
                    $this->locale
1265
                );
1266
            }
1267
        } else {
1268
            $parentsAreOk = true;
1269
        }
1270
1271
        return $this->render(
1272
            'KunstmaanNodeBundle:NodeAdmin:pagenottranslated.html.twig',
1273
            array(
1274
                'node' => $node,
1275
                'nodeTranslations' => $node->getNodeTranslations(
1276
                    true
1277
                ),
1278
                'copyfromotherlanguages' => $parentsAreOk,
1279
            )
1280
        );
1281
    }
1282
}
1283