Completed
Pull Request — 5.3 (#2650)
by Jeroen
21:04 queued 15:00
created

NodeHelper   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 494
Duplicated Lines 18.02 %

Coupling/Cohesion

Components 1
Dependencies 16

Test Coverage

Coverage 96.96%

Importance

Changes 0
Metric Value
wmc 32
lcom 1
cbo 16
dl 89
loc 494
ccs 223
cts 230
cp 0.9696
rs 9.84
c 0
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 13 13 1
A createDraftVersion() 0 40 1
A prepareNodeVersion() 18 25 4
A updatePage() 0 37 4
A createPage() 0 48 4
A deletePage() 0 24 1
A getPageWithNodeInterface() 0 7 1
A copyPageFromOtherLanguage() 29 29 1
A duplicatePage() 0 29 3
A createPageDraftFromOtherLanguage() 29 29 1
A createEmptyPage() 0 18 1
A createNewPage() 0 11 1
A deleteNodeChildren() 0 36 2
A getUser() 0 12 5
A getAdminUser() 0 9 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\User;
7
use Kunstmaan\AdminBundle\Helper\CloneHelper;
8
use Kunstmaan\AdminBundle\Helper\FormWidgets\Tabs\TabPane;
9
use Kunstmaan\NodeBundle\Entity\HasNodeInterface;
10
use Kunstmaan\NodeBundle\Entity\Node;
11
use Kunstmaan\NodeBundle\Entity\NodeTranslation;
12
use Kunstmaan\NodeBundle\Entity\NodeVersion;
13
use Kunstmaan\NodeBundle\Event\CopyPageTranslationNodeEvent;
14
use Kunstmaan\NodeBundle\Event\Events;
15
use Kunstmaan\NodeBundle\Event\NodeEvent;
16
use Kunstmaan\NodeBundle\Event\RecopyPageTranslationNodeEvent;
17
use Kunstmaan\NodeBundle\Helper\NodeAdmin\NodeAdminPublisher;
18
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
19
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
20
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
21
22
/**
23
 * Class NodeHelper
24
 */
25
class NodeHelper
26
{
27
    /** @var EntityManagerInterface */
28
    private $em;
29
30
    /** @var NodeAdminPublisher */
31
    private $nodeAdminPublisher;
32
33
    /** @var TokenStorageInterface */
34
    private $tokenStorage;
35
36
    /** @var CloneHelper */
37
    private $cloneHelper;
38
39
    /** @var EventDispatcherInterface */
40
    private $eventDispatcher;
41
42
    /**
43
     * NodeHelper constructor.
44
     *
45
     * @param EntityManagerInterface   $em
46
     * @param NodeAdminPublisher       $nodeAdminPublisher
47
     * @param TokenStorageInterface    $tokenStorage
48
     * @param CloneHelper              $cloneHelper
49
     * @param EventDispatcherInterface $eventDispatcher
50
     */
51 12 View Code Duplication
    public function __construct(
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...
52
        EntityManagerInterface $em,
53
        NodeAdminPublisher $nodeAdminPublisher,
54
        TokenStorageInterface $tokenStorage,
55
        CloneHelper $cloneHelper,
56
        EventDispatcherInterface $eventDispatcher
57
    ) {
58 12
        $this->em = $em;
59 12
        $this->nodeAdminPublisher = $nodeAdminPublisher;
60 12
        $this->tokenStorage = $tokenStorage;
61 12
        $this->cloneHelper = $cloneHelper;
62 12
        $this->eventDispatcher = $eventDispatcher;
63 12
    }
64
65
    /**
66
     * @param HasNodeInterface $page            The page
67
     * @param NodeTranslation  $nodeTranslation The node translation
68
     * @param NodeVersion      $nodeVersion     The node version
69
     *
70
     * @return NodeVersion
71
     */
72 1
    public function createDraftVersion(
73
        HasNodeInterface $page,
74
        NodeTranslation $nodeTranslation,
75
        NodeVersion $nodeVersion
76
    ) {
77 1
        $user = $this->getAdminUser();
78 1
        $publicPage = $this->cloneHelper->deepCloneAndSave($page);
79
80
        /* @var NodeVersion $publicNodeVersion */
81 1
        $publicNodeVersion = $this->em->getRepository('KunstmaanNodeBundle:NodeVersion')
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 createNodeVersionFor() does only exist in the following implementations of said interface: Kunstmaan\NodeBundle\Rep...y\NodeVersionRepository.

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...
82 1
            ->createNodeVersionFor(
83 1
                $publicPage,
84 1
                $nodeTranslation,
85 1
                $user,
86 1
                $nodeVersion->getOrigin(),
87 1
                NodeVersion::PUBLIC_VERSION,
88 1
                $nodeVersion->getCreated()
89
            );
90
91 1
        $nodeTranslation->setPublicNodeVersion($publicNodeVersion);
92 1
        $nodeVersion->setType(NodeVersion::DRAFT_VERSION);
93 1
        $nodeVersion->setOrigin($publicNodeVersion);
94 1
        $nodeVersion->setCreated(new \DateTime());
95
96 1
        $this->em->persist($nodeTranslation);
97 1
        $this->em->persist($nodeVersion);
98 1
        $this->em->flush();
99
100 1
        $this->eventDispatcher->dispatch(
101 1
            Events::CREATE_DRAFT_VERSION,
102 1
            new NodeEvent(
103 1
                $nodeTranslation->getNode(),
104 1
                $nodeTranslation,
105 1
                $nodeVersion,
106 1
                $page
107
            )
108
        );
109
110 1
        return $nodeVersion;
111
    }
112
113
    /**
114
     * @param NodeVersion     $nodeVersion
115
     * @param NodeTranslation $nodeTranslation
116
     * @param int             $nodeVersionTimeout
117
     * @param bool            $nodeVersionIsLocked
118
     */
119 2
    public function prepareNodeVersion(NodeVersion $nodeVersion, NodeTranslation $nodeTranslation, $nodeVersionTimeout, $nodeVersionIsLocked)
120
    {
121 2
        $user = $this->getAdminUser();
122 2
        $thresholdDate = date('Y-m-d H:i:s', time() - $nodeVersionTimeout);
123 2
        $updatedDate = date('Y-m-d H:i:s', strtotime($nodeVersion->getUpdated()->format('Y-m-d H:i:s')));
124
125 2 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...
126 2
            $page = $nodeVersion->getRef($this->em);
0 ignored issues
show
Compatibility introduced by
$this->em of type object<Doctrine\ORM\EntityManagerInterface> is not a sub-type of object<Doctrine\ORM\EntityManager>. It seems like you assume a concrete implementation of the interface Doctrine\ORM\EntityManagerInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
127 2
            if ($nodeVersion === $nodeTranslation->getPublicNodeVersion()) {
128 1
                $this->nodeAdminPublisher
129 1
                    ->createPublicVersion(
130 1
                        $page,
0 ignored issues
show
Bug introduced by
It seems like $page defined by $nodeVersion->getRef($this->em) on line 126 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...
131 1
                        $nodeTranslation,
132 1
                        $nodeVersion,
133 1
                        $user
134
                    );
135
            } else {
136 1
                $this->createDraftVersion(
137 1
                    $page,
0 ignored issues
show
Bug introduced by
It seems like $page defined by $nodeVersion->getRef($this->em) on line 126 can be null; however, Kunstmaan\NodeBundle\Hel...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...
138 1
                    $nodeTranslation,
139 1
                    $nodeVersion
140
                );
141
            }
142
        }
143 2
    }
144
145
    /**
146
     * @param Node             $node
147
     * @param NodeTranslation  $nodeTranslation
148
     * @param NodeVersion      $nodeVersion
149
     * @param HasNodeInterface $page
150
     * @param bool             $isStructureNode
151
     * @param TabPane          $tabPane
0 ignored issues
show
Documentation introduced by
Should the type for parameter $tabPane not be null|TabPane?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
152
     *
153
     * @return NodeTranslation
154
     */
155 1
    public function updatePage(
156
        Node $node,
157
        NodeTranslation $nodeTranslation,
158
        NodeVersion $nodeVersion,
159
        HasNodeInterface $page,
160
        $isStructureNode,
161
        TabPane $tabPane = null
162
    ) {
163 1
        $this->eventDispatcher->dispatch(
164 1
            Events::PRE_PERSIST,
165 1
            new NodeEvent($node, $nodeTranslation, $nodeVersion, $page)
166
        );
167
168 1
        $nodeTranslation->setTitle($page->getTitle());
169 1
        if ($isStructureNode) {
170
            $nodeTranslation->setSlug('');
171
        }
172
173 1
        $nodeVersion->setUpdated(new \DateTime());
174 1
        if ($nodeVersion->getType() == NodeVersion::PUBLIC_VERSION) {
175 1
            $nodeTranslation->setUpdated($nodeVersion->getUpdated());
176
        }
177 1
        $this->em->persist($nodeTranslation);
178 1
        $this->em->persist($nodeVersion);
179 1
        $this->em->persist($node);
180 1
        if (null !== $tabPane) {
181
            $tabPane->persist($this->em);
0 ignored issues
show
Compatibility introduced by
$this->em of type object<Doctrine\ORM\EntityManagerInterface> is not a sub-type of object<Doctrine\ORM\EntityManager>. It seems like you assume a concrete implementation of the interface Doctrine\ORM\EntityManagerInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
182
        }
183 1
        $this->em->flush();
184
185 1
        $this->eventDispatcher->dispatch(
186 1
            Events::POST_PERSIST,
187 1
            new NodeEvent($node, $nodeTranslation, $nodeVersion, $page)
188
        );
189
190 1
        return $nodeTranslation;
191
    }
192
193
    /**
194
     * @param string    $refEntityType
195
     * @param string    $pageTitle
196
     * @param string    $locale
197
     * @param Node|null $parentNode
198
     *
199
     * @return NodeTranslation
0 ignored issues
show
Documentation introduced by
Should the return type not be NodeTranslation|null?

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...
200
     */
201 1
    public function createPage(
202
        $refEntityType,
203
        $pageTitle,
204
        $locale,
205
        Node $parentNode = null
206
    ) {
207 1
        $user = $this->getAdminUser();
208
209 1
        $newPage = $this->createNewPage($refEntityType, $pageTitle);
210 1
        if (null !== $parentNode) {
211 1
            $parentNodeTranslation = $parentNode->getNodeTranslation($locale, true);
212 1
            $parentNodeVersion = $parentNodeTranslation->getPublicNodeVersion();
213 1
            $parentPage = $parentNodeVersion->getRef($this->em);
214 1
            $newPage->setParent($parentPage);
215
        }
216
217
        /* @var Node $nodeNewPage */
218 1
        $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...
219 1
        $nodeTranslation = $nodeNewPage->getNodeTranslation($locale, true);
220 1
        if (null !== $parentNode) {
221 1
            $weight = $this->em->getRepository('KunstmaanNodeBundle:NodeTranslation')->getMaxChildrenWeight(
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 getMaxChildrenWeight() does only exist in the following implementations of said interface: Kunstmaan\NodeBundle\Rep...deTranslationRepository.

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...
222 1
                $parentNode,
223 1
                $locale
224 1
            ) + 1;
225 1
            $nodeTranslation->setWeight($weight);
226
        }
227
228 1
        if ($newPage->isStructureNode()) {
229
            $nodeTranslation->setSlug('');
230
        }
231
232 1
        $this->em->persist($nodeTranslation);
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $nodeNewPage->getNodeTranslation($locale, true) on line 219 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...
233 1
        $this->em->flush();
234
235 1
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
236
237 1
        $this->eventDispatcher->dispatch(
238 1
            Events::ADD_NODE,
239 1
            new NodeEvent(
240 1
                $nodeNewPage,
241 1
                $nodeTranslation,
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $nodeNewPage->getNodeTranslation($locale, true) on line 219 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...
242 1
                $nodeVersion,
243 1
                $newPage
244
            )
245
        );
246
247 1
        return $nodeTranslation;
248
    }
249
250
    /**
251
     * @param Node   $node
252
     * @param string $locale
253
     *
254
     * @return NodeTranslation
0 ignored issues
show
Documentation introduced by
Should the return type not be NodeTranslation|null?

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...
255
     */
256 1
    public function deletePage(Node $node, $locale)
257
    {
258 1
        $nodeTranslation = $node->getNodeTranslation($locale, true);
259 1
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
260 1
        $page = $nodeVersion->getRef($this->em);
261
262 1
        $this->eventDispatcher->dispatch(
263 1
            Events::PRE_DELETE,
264 1
            new NodeEvent($node, $nodeTranslation, $nodeVersion, $page)
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $node->getNodeTranslation($locale, true) on line 258 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...
265
        );
266
267 1
        $node->setDeleted(true);
268 1
        $this->em->persist($node);
269
270 1
        $this->deleteNodeChildren($node, $locale);
271 1
        $this->em->flush();
272
273 1
        $this->eventDispatcher->dispatch(
274 1
            Events::POST_DELETE,
275 1
            new NodeEvent($node, $nodeTranslation, $nodeVersion, $page)
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $node->getNodeTranslation($locale, true) on line 258 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...
276
        );
277
278 1
        return $nodeTranslation;
279
    }
280
281
    /**
282
     * @param Node   $node
283
     * @param string $locale
284
     *
285
     * @return HasNodeInterface
286
     */
287 1
    public function getPageWithNodeInterface(Node $node, $locale)
288
    {
289 1
        $nodeTranslation = $node->getNodeTranslation($locale, true);
290 1
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
291
292 1
        return $nodeVersion->getRef($this->em);
293
    }
294
295
    /**
296
     * @param Node   $node
297
     * @param string $sourceLocale
298
     * @param string $locale
299
     *
300
     * @return NodeTranslation
301
     */
302 1 View Code Duplication
    public function copyPageFromOtherLanguage(Node $node, $sourceLocale, $locale)
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...
303
    {
304 1
        $user = $this->getAdminUser();
305
306 1
        $sourceNodeTranslation = $node->getNodeTranslation($sourceLocale, true);
307 1
        $sourceNodeVersion = $sourceNodeTranslation->getPublicNodeVersion();
308 1
        $sourcePage = $sourceNodeVersion->getRef($this->em);
309 1
        $targetPage = $this->cloneHelper->deepCloneAndSave($sourcePage);
310
311
        /* @var NodeTranslation $nodeTranslation */
312 1
        $nodeTranslation = $this->em->getRepository(NodeTranslation::class)->createNodeTranslationFor($targetPage, $locale, $node, $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 createNodeTranslationFor() does only exist in the following implementations of said interface: Kunstmaan\NodeBundle\Rep...deTranslationRepository.

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...
313 1
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
314
315 1
        $this->eventDispatcher->dispatch(
316 1
            Events::COPY_PAGE_TRANSLATION,
317 1
            new CopyPageTranslationNodeEvent(
318 1
                $node,
319 1
                $nodeTranslation,
320 1
                $nodeVersion,
321 1
                $targetPage,
322 1
                $sourceNodeTranslation,
0 ignored issues
show
Bug introduced by
It seems like $sourceNodeTranslation defined by $node->getNodeTranslation($sourceLocale, true) on line 306 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...
323 1
                $sourceNodeVersion,
324 1
                $sourcePage,
325 1
                $sourceLocale
326
            )
327
        );
328
329 1
        return $nodeTranslation;
330
    }
331
332
    /**
333
     * @param Node   $node
334
     * @param string $locale
335
     * @param string $title
336
     *
337
     * @return NodeTranslation|null
338
     */
339 1
    public function duplicatePage(Node $node, $locale, $title = 'New page')
340
    {
341 1
        $user = $this->getAdminUser();
342
343 1
        $sourceNodeTranslations = $node->getNodeTranslation($locale, true);
344 1
        $sourcePage = $sourceNodeTranslations->getPublicNodeVersion()->getRef($this->em);
345 1
        $targetPage = $this->cloneHelper->deepCloneAndSave($sourcePage);
346 1
        $targetPage->setTitle($title);
347
348 1
        if ($node->getParent()) {
349 1
            $parentNodeTranslation = $node->getParent()->getNodeTranslation($locale, true);
350 1
            $parent = $parentNodeTranslation->getPublicNodeVersion()->getRef($this->em);
351 1
            $targetPage->setParent($parent);
352
        }
353 1
        $this->em->persist($targetPage);
354 1
        $this->em->flush();
355
356
        /* @var Node $nodeNewPage */
357 1
        $nodeNewPage = $this->em->getRepository(Node::class)->createNodeFor($targetPage, $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...
358
359 1
        $nodeTranslation = $nodeNewPage->getNodeTranslation($locale, true);
360 1
        if ($targetPage->isStructureNode()) {
361
            $nodeTranslation->setSlug('');
362
            $this->em->persist($nodeTranslation);
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $nodeNewPage->getNodeTranslation($locale, true) on line 359 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...
363
        }
364 1
        $this->em->flush();
365
366 1
        return $nodeTranslation;
367
    }
368
369
    /**
370
     * @param Node   $node
371
     * @param int    $sourceNodeTranslationId
372
     * @param string $locale
373
     *
374
     * @return NodeTranslation
375
     */
376 1 View Code Duplication
    public function createPageDraftFromOtherLanguage(Node $node, $sourceNodeTranslationId, $locale)
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...
377
    {
378 1
        $user = $this->getAdminUser();
379
380 1
        $sourceNodeTranslation = $this->em->getRepository(NodeTranslation::class)->find($sourceNodeTranslationId);
381 1
        $sourceNodeVersion = $sourceNodeTranslation->getPublicNodeVersion();
382 1
        $sourcePage = $sourceNodeVersion->getRef($this->em);
383 1
        $targetPage = $this->cloneHelper->deepCloneAndSave($sourcePage);
384
385
        /* @var NodeTranslation $nodeTranslation */
386 1
        $nodeTranslation = $this->em->getRepository(NodeTranslation::class)->addDraftNodeVersionFor($targetPage, $locale, $node, $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 addDraftNodeVersionFor() does only exist in the following implementations of said interface: Kunstmaan\NodeBundle\Rep...deTranslationRepository.

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...
387 1
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
388
389 1
        $this->eventDispatcher->dispatch(
390 1
            Events::RECOPY_PAGE_TRANSLATION,
391 1
            new RecopyPageTranslationNodeEvent(
392 1
                $node,
393 1
                $nodeTranslation,
394 1
                $nodeVersion,
395 1
                $targetPage,
396 1
                $sourceNodeTranslation,
0 ignored issues
show
Documentation introduced by
$sourceNodeTranslation 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...
397 1
                $sourceNodeVersion,
398 1
                $sourcePage,
399 1
                $sourceNodeTranslation->getLang()
400
            )
401
        );
402
403 1
        return $nodeTranslation;
404
    }
405
406
    /**
407
     * @param Node   $node
408
     * @param string $locale
409
     *
410
     * @return NodeTranslation
411
     */
412 1
    public function createEmptyPage(Node $node, $locale)
413
    {
414 1
        $user = $this->getAdminUser();
415
416 1
        $refEntityName = $node->getRefEntityName();
417 1
        $targetPage = $this->createNewPage($refEntityName);
418
419
        /* @var NodeTranslation $nodeTranslation */
420 1
        $nodeTranslation = $this->em->getRepository(NodeTranslation::class)->createNodeTranslationFor($targetPage, $locale, $node, $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 createNodeTranslationFor() does only exist in the following implementations of said interface: Kunstmaan\NodeBundle\Rep...deTranslationRepository.

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...
421 1
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
422
423 1
        $this->eventDispatcher->dispatch(
424 1
            Events::ADD_EMPTY_PAGE_TRANSLATION,
425 1
            new NodeEvent($node, $nodeTranslation, $nodeVersion, $targetPage)
426
        );
427
428 1
        return $nodeTranslation;
429
    }
430
431
    /**
432
     * @param string $entityType
433
     * @param string $title
434
     *
435
     * @return HasNodeInterface
436
     */
437 2
    protected function createNewPage($entityType, $title = 'No title')
438
    {
439
        /* @var HasNodeInterface $newPage */
440 2
        $newPage = new $entityType();
441 2
        $newPage->setTitle($title);
442
443 2
        $this->em->persist($newPage);
444 2
        $this->em->flush();
445
446 2
        return $newPage;
447
    }
448
449
    /**
450
     * @param Node   $node
451
     * @param string $locale
452
     */
453 1
    protected function deleteNodeChildren(Node $node, $locale)
454
    {
455 1
        $children = $node->getChildren();
456
457
        /* @var Node $childNode */
458 1
        foreach ($children as $childNode) {
459 1
            $childNodeTranslation = $childNode->getNodeTranslation($locale, true);
460 1
            $childNodeVersion = $childNodeTranslation->getPublicNodeVersion();
461 1
            $childNodePage = $childNodeVersion->getRef($this->em);
462
463 1
            $this->eventDispatcher->dispatch(
464 1
                Events::PRE_DELETE,
465 1
                new NodeEvent(
466 1
                    $childNode,
467 1
                    $childNodeTranslation,
468 1
                    $childNodeVersion,
469 1
                    $childNodePage
470
                )
471
            );
472
473 1
            $childNode->setDeleted(true);
474 1
            $this->em->persist($childNode);
475
476 1
            $this->deleteNodeChildren($childNode, $locale);
477
478 1
            $this->eventDispatcher->dispatch(
479 1
                Events::POST_DELETE,
480 1
                new NodeEvent(
481 1
                    $childNode,
482 1
                    $childNodeTranslation,
483 1
                    $childNodeVersion,
484 1
                    $childNodePage
485
                )
486
            );
487
        }
488 1
    }
489
490
    /**
491
     * @return mixed|null
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use User|null.

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...
492
     */
493 8
    protected function getUser()
494
    {
495 8
        $token = $this->tokenStorage->getToken();
496 8
        if ($token) {
497 8
            $user = $token->getUser();
498 8
            if ($user && $user !== 'anon.' && $user instanceof User) {
499 8
                return $user;
500
            }
501
        }
502
503
        return null;
504
    }
505
506
    /**
507
     * @return mixed
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use User.

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...
508
     */
509 8
    protected function getAdminUser()
510
    {
511 8
        $user = $this->getUser();
512 8
        if (!$user) {
513
            throw new AccessDeniedException('Access denied: User should be an admin user');
514
        }
515
516 8
        return $user;
517
    }
518
}
519