PageCloningHelper   A
last analyzed

Complexity

Total Complexity 17

Size/Duplication

Total Lines 157
Duplicated Lines 17.83 %

Coupling/Cohesion

Components 1
Dependencies 15

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 15
dl 28
loc 157
ccs 0
cts 95
cp 0
c 0
b 0
f 0
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A duplicateWithChildren() 0 18 1
A denyAccessUnlessGranted() 0 10 2
A clonePage() 0 21 2
A createNodeStructureForNewPage() 0 16 2
A updateAcl() 18 18 3
A cloneChildren() 0 18 4
A dispatch() 10 10 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\EventDispatcher\LegacyEventDispatcherProxy;
18
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
19
use Symfony\Component\Security\Acl\Model\AclProviderInterface;
20
use Symfony\Component\Security\Acl\Model\EntryInterface;
21
use Symfony\Component\Security\Acl\Model\ObjectIdentityRetrievalStrategyInterface;
22
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
23
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
24
25
class PageCloningHelper
26
{
27
    /** @var EntityManagerInterface */
28
    private $em;
29
30
    /** @var CloneHelper */
31
    private $cloneHelper;
32
33
    /** @var AclProviderInterface */
34
    private $aclProvider;
35
36
    /** @var ObjectIdentityRetrievalStrategyInterface */
37
    private $identityRetrievalStrategy;
38
39
    /** @var AuthorizationCheckerInterface */
40
    private $authorizationCheckerInterface;
41
42
    /** @var EventDispatcherInterface */
43
    private $eventDispatcherInterface;
44
45
    public function __construct(EntityManagerInterface $em, CloneHelper $cloneHelper, AclProviderInterface $aclProvider, ObjectIdentityRetrievalStrategyInterface $identityRetrivalStrategy, AuthorizationCheckerInterface $authorizationChecker, EventDispatcherInterface $eventDispatcher)
46
    {
47
        $this->em = $em;
48
        $this->cloneHelper = $cloneHelper;
49
        $this->aclProvider = $aclProvider;
50
        $this->identityRetrievalStrategy = $identityRetrivalStrategy;
51
        $this->authorizationCheckerInterface = $authorizationChecker;
52
        $this->eventDispatcherInterface = $eventDispatcher;
53
    }
54
55
    /**
56
     * @throws AccessDeniedException
57
     */
58
    public function duplicateWithChildren($id, string $locale, BaseUser $user, string $title = null): Node
59
    {
60
        /* @var Node $parentNode */
61
        $originalNode = $this->em->getRepository('KunstmaanNodeBundle:Node')->find($id);
62
63
        $this->denyAccessUnlessGranted(PermissionMap::PERMISSION_EDIT, $originalNode);
64
65
        $this->dispatch(new PreNodeDuplicateEvent($originalNode), Events::PRE_DUPLICATE_WITH_CHILDREN);
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...
66
67
        $newPage = $this->clonePage($originalNode, $locale, $title);
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...
68
        $nodeNewPage = $this->createNodeStructureForNewPage($originalNode, $newPage, $user, $locale);
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...
69
70
        $this->dispatch(new PostNodeDuplicateEvent($originalNode, $nodeNewPage, $newPage), Events::POST_DUPLICATE_WITH_CHILDREN);
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...
71
72
        $this->cloneChildren($originalNode, $newPage, $user, $locale);
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...
73
74
        return $nodeNewPage;
75
    }
76
77
    private function denyAccessUnlessGranted($attributes, $subject = null, $message = 'Access Denied.')
78
    {
79
        if (!$this->authorizationCheckerInterface->isGranted($attributes, $subject)) {
80
            $exception = new AccessDeniedException();
81
            $exception->setAttributes($attributes);
82
            $exception->setSubject($subject);
83
84
            throw $exception;
85
        }
86
    }
87
88
    public function clonePage(Node $originalNode, $locale, $title = null)
89
    {
90
        $originalNodeTranslations = $originalNode->getNodeTranslation($locale, true);
91
        $originalRef = $originalNodeTranslations->getPublicNodeVersion()->getRef($this->em);
92
93
        $newPage = $this->cloneHelper->deepCloneAndSave($originalRef);
94
95
        if ($title !== null) {
96
            $newPage->setTitle($title);
97
        }
98
99
        //set the parent
100
        $parentNodeTranslation = $originalNode->getParent()->getNodeTranslation($locale, true);
101
        $parent = $parentNodeTranslation->getPublicNodeVersion()->getRef($this->em);
102
        $newPage->setParent($parent);
103
104
        $this->em->persist($newPage);
105
        $this->em->flush();
106
107
        return $newPage;
108
    }
109
110
    private function createNodeStructureForNewPage(Node $originalNode, HasNodeInterface $newPage, BaseUser $user, string $locale): Node
111
    {
112
        /* @var Node $nodeNewPage */
113
        $nodeNewPage = $this->em->getRepository('KunstmaanNodeBundle:Node')->createNodeFor($newPage, $locale, $user);
0 ignored issues
show
Bug introduced by
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...
114
115
        if ($newPage->isStructureNode()) {
116
            $nodeTranslation = $nodeNewPage->getNodeTranslation($locale, true);
117
            $nodeTranslation->setSlug('');
118
            $this->em->persist($nodeTranslation);
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $nodeNewPage->getNodeTranslation($locale, true) on line 116 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...
119
        }
120
        $this->em->flush();
121
122
        $this->updateAcl($originalNode, $nodeNewPage);
123
124
        return $nodeNewPage;
125
    }
126
127 View Code Duplication
    private function updateAcl($originalNode, $nodeNewPage): void
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...
128
    {
129
        $originalIdentity = $this->identityRetrievalStrategy->getObjectIdentity($originalNode);
130
        $originalAcl = $this->aclProvider->findAcl($originalIdentity);
131
132
        $newIdentity = $this->identityRetrievalStrategy->getObjectIdentity($nodeNewPage);
133
        $newAcl = $this->aclProvider->createAcl($newIdentity);
0 ignored issues
show
Bug introduced by
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...
134
135
        $aces = $originalAcl->getObjectAces();
136
        /* @var EntryInterface $ace */
137
        foreach ($aces as $ace) {
138
            $securityIdentity = $ace->getSecurityIdentity();
139
            if ($securityIdentity instanceof RoleSecurityIdentity) {
140
                $newAcl->insertObjectAce($securityIdentity, $ace->getMask());
141
            }
142
        }
143
        $this->aclProvider->updateAcl($newAcl);
0 ignored issues
show
Bug introduced by
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...
144
    }
145
146
    private function cloneChildren(Node $originalNode, PageInterface $newPage, BaseUser $user, string $locale): void
147
    {
148
        $nodeChildren = $originalNode->getChildren();
149
        foreach ($nodeChildren as $originalNodeChild) {
150
            $originalNodeTranslations = $originalNodeChild->getNodeTranslation($locale, true);
151
            $originalRef = $originalNodeTranslations->getPublicNodeVersion()->getRef($this->em);
152
153
            if (!$originalRef instanceof DuplicateSubPageInterface || !$originalRef->skipClone()) {
154
                $this->dispatch(new PreNodeDuplicateEvent($originalNodeChild), Events::PRE_DUPLICATE_WITH_CHILDREN);
155
                $newChildPage = $this->clonePage($originalNodeChild, $locale);
156
                $newChildPage->setParent($newPage);
157
158
                $newChildNode = $this->createNodeStructureForNewPage($originalNodeChild, $newChildPage, $user, $locale);
159
                $this->dispatch(new PostNodeDuplicateEvent($originalNodeChild, $newChildNode, $newChildPage), Events::POST_DUPLICATE_WITH_CHILDREN);
160
                $this->cloneChildren($originalNodeChild, $newChildPage, $user, $locale);
161
            }
162
        }
163
    }
164
165
    /**
166
     * @param object $event
167
     * @param string $eventName
168
     *
169
     * @return object
170
     */
171 View Code Duplication
    private function dispatch($event, string $eventName)
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...
172
    {
173
        if (class_exists(LegacyEventDispatcherProxy::class)) {
174
            $eventDispatcher = LegacyEventDispatcherProxy::decorate($this->eventDispatcherInterface);
175
176
            return $eventDispatcher->dispatch($event, $eventName);
177
        }
178
179
        return $this->eventDispatcherInterface->dispatch($eventName, $event);
180
    }
181
}
182