Completed
Push — master ( eab2a6...645cff )
by Jeroen
30s queued 13s
created

Kunstmaan/NodeBundle/Helper/PageCloningHelper.php (9 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Kunstmaan\NodeBundle\Helper;
4
5
use Doctrine\ORM\EntityManagerInterface;
6
use Kunstmaan\AdminBundle\Entity\BaseUser;
7
use Kunstmaan\AdminBundle\Helper\CloneHelper;
8
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionMap;
9
use Kunstmaan\NodeBundle\Entity\DuplicateSubPageInterface;
10
use Kunstmaan\NodeBundle\Entity\HasNodeInterface;
11
use Kunstmaan\NodeBundle\Entity\Node;
12
use Kunstmaan\NodeBundle\Entity\PageInterface;
13
use Kunstmaan\NodeBundle\Event\Events;
14
use Kunstmaan\NodeBundle\Event\PreNodeDuplicateEvent;
15
use Kunstmaan\NodeBundle\Event\PostNodeDuplicateEvent;
16
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
17
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
18
use Symfony\Component\Security\Acl\Model\AclProviderInterface;
19
use Symfony\Component\Security\Acl\Model\EntryInterface;
20
use Symfony\Component\Security\Acl\Model\ObjectIdentityRetrievalStrategyInterface;
21
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
22
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
23
24
class PageCloningHelper
25
{
26
    /** @var EntityManagerInterface */
27
    private $em;
28
29
    /** @var CloneHelper */
30
    private $cloneHelper;
31
32
    /** @var AclProviderInterface */
33
    private $aclProvider;
34
35
    /** @var ObjectIdentityRetrievalStrategyInterface */
36
    private $identityRetrievalStrategy;
37
38
    /** @var AuthorizationCheckerInterface */
39
    private $authorizationCheckerInterface;
40
41
    /** @var EventDispatcherInterface */
42
    private $eventDispatcherInterface;
43
44
    public function __construct(EntityManagerInterface $em, CloneHelper $cloneHelper, AclProviderInterface $aclProvider, ObjectIdentityRetrievalStrategyInterface $identityRetrivalStrategy, AuthorizationCheckerInterface $authorizationChecker, EventDispatcherInterface $eventDispatcher)
45
    {
46
        $this->em = $em;
47
        $this->cloneHelper = $cloneHelper;
48
        $this->aclProvider = $aclProvider;
49
        $this->identityRetrievalStrategy = $identityRetrivalStrategy;
50
        $this->authorizationCheckerInterface = $authorizationChecker;
51
        $this->eventDispatcherInterface = $eventDispatcher;
52
    }
53
54
    /**
55
     * @throws AccessDeniedException
56
     */
57
    public function duplicateWithChildren($id, string $locale, BaseUser $user, string $title = null): Node
58
    {
59
        /* @var Node $parentNode */
60
        $originalNode = $this->em->getRepository('KunstmaanNodeBundle:Node')->find($id);
61
62
        $this->denyAccessUnlessGranted(PermissionMap::PERMISSION_EDIT, $originalNode);
63
64
        $this->eventDispatcherInterface->dispatch(Events::PRE_DUPLICATE_WITH_CHILDREN, new PreNodeDuplicateEvent($originalNode));
0 ignored issues
show
$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...
65
66
        $newPage = $this->clonePage($originalNode, $locale, $title);
0 ignored issues
show
$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...
67
        $nodeNewPage = $this->createNodeStructureForNewPage($originalNode, $newPage, $user, $locale);
0 ignored issues
show
$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...
68
69
        $this->eventDispatcherInterface->dispatch(Events::POST_DUPLICATE_WITH_CHILDREN, new PostNodeDuplicateEvent($originalNode, $nodeNewPage, $newPage));
0 ignored issues
show
$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...
70
71
        $this->cloneChildren($originalNode, $newPage, $user, $locale);
0 ignored issues
show
$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...
72
73
        return $nodeNewPage;
74
    }
75
76
    private function denyAccessUnlessGranted($attributes, $subject = null, $message = 'Access Denied.')
77
    {
78
        if (!$this->authorizationCheckerInterface->isGranted($attributes, $subject)) {
79
            $exception = new AccessDeniedException();
80
            $exception->setAttributes($attributes);
81
            $exception->setSubject($subject);
82
83
            throw $exception;
84
        }
85
    }
86
87
    public function clonePage(Node $originalNode, $locale, $title = null)
88
    {
89
        $originalNodeTranslations = $originalNode->getNodeTranslation($locale, true);
90
        $originalRef = $originalNodeTranslations->getPublicNodeVersion()->getRef($this->em);
91
92
        $newPage = $this->cloneHelper->deepCloneAndSave($originalRef);
93
94
        if ($title !== null) {
95
            $newPage->setTitle($title);
96
        }
97
98
        //set the parent
99
        $parentNodeTranslation = $originalNode->getParent()->getNodeTranslation($locale, true);
100
        $parent = $parentNodeTranslation->getPublicNodeVersion()->getRef($this->em);
101
        $newPage->setParent($parent);
102
103
        $this->em->persist($newPage);
104
        $this->em->flush();
105
106
        return $newPage;
107
    }
108
109
    private function createNodeStructureForNewPage(Node $originalNode, HasNodeInterface $newPage, BaseUser $user, string $locale): Node
110
    {
111
        /* @var Node $nodeNewPage */
112
        $nodeNewPage = $this->em->getRepository('KunstmaanNodeBundle:Node')->createNodeFor($newPage, $locale, $user);
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Doctrine\Persistence\ObjectRepository as the method createNodeFor() does only exist in the following implementations of said interface: Kunstmaan\NodeBundle\Repository\NodeRepository.

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...
113
114
        if ($newPage->isStructureNode()) {
115
            $nodeTranslation = $nodeNewPage->getNodeTranslation($locale, true);
116
            $nodeTranslation->setSlug('');
117
            $this->em->persist($nodeTranslation);
0 ignored issues
show
It seems like $nodeTranslation defined by $nodeNewPage->getNodeTranslation($locale, true) on line 115 can be null; however, Doctrine\Persistence\ObjectManager::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...
118
        }
119
        $this->em->flush();
120
121
        $this->updateAcl($originalNode, $nodeNewPage);
122
123
        return $nodeNewPage;
124
    }
125
126 View Code Duplication
    private function updateAcl($originalNode, $nodeNewPage): void
127
    {
128
        $originalIdentity = $this->identityRetrievalStrategy->getObjectIdentity($originalNode);
129
        $originalAcl = $this->aclProvider->findAcl($originalIdentity);
130
131
        $newIdentity = $this->identityRetrievalStrategy->getObjectIdentity($nodeNewPage);
132
        $newAcl = $this->aclProvider->createAcl($newIdentity);
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Symfony\Component\Securi...el\AclProviderInterface as the method createAcl() does only exist in the following implementations of said interface: Symfony\Component\Securi...Dbal\MutableAclProvider.

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
134
        $aces = $originalAcl->getObjectAces();
135
        /* @var EntryInterface $ace */
136
        foreach ($aces as $ace) {
137
            $securityIdentity = $ace->getSecurityIdentity();
138
            if ($securityIdentity instanceof RoleSecurityIdentity) {
139
                $newAcl->insertObjectAce($securityIdentity, $ace->getMask());
140
            }
141
        }
142
        $this->aclProvider->updateAcl($newAcl);
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Symfony\Component\Securi...el\AclProviderInterface as the method updateAcl() does only exist in the following implementations of said interface: Symfony\Component\Securi...Dbal\MutableAclProvider.

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...
143
    }
144
145
    private function cloneChildren(Node $originalNode, PageInterface $newPage, BaseUser $user, string $locale): void
146
    {
147
        $nodeChildren = $originalNode->getChildren();
148
        foreach ($nodeChildren as $originalNodeChild) {
149
            $originalNodeTranslations = $originalNodeChild->getNodeTranslation($locale, true);
150
            $originalRef = $originalNodeTranslations->getPublicNodeVersion()->getRef($this->em);
151
152
            if (!$originalRef instanceof DuplicateSubPageInterface || !$originalRef->skipClone()) {
153
                $this->eventDispatcherInterface->dispatch(Events::PRE_DUPLICATE_WITH_CHILDREN, new PreNodeDuplicateEvent($originalNodeChild));
154
                $newChildPage = $this->clonePage($originalNodeChild, $locale);
155
                $newChildPage->setParent($newPage);
156
157
                $newChildNode = $this->createNodeStructureForNewPage($originalNodeChild, $newChildPage, $user, $locale);
158
                $this->eventDispatcherInterface->dispatch(Events::POST_DUPLICATE_WITH_CHILDREN, new PostNodeDuplicateEvent($originalNodeChild, $newChildNode, $newChildPage));
159
                $this->cloneChildren($originalNodeChild, $newChildPage, $user, $locale);
160
            }
161
        }
162
    }
163
}
164