Completed
Pull Request — master (#2743)
by Jeroen
14:54
created

NodeHelper::dispatch()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 10
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 10
loc 10
c 0
b 0
f 0
ccs 0
cts 0
cp 0
rs 9.9332
cc 2
nc 2
nop 2
crap 6
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\EventDispatcher\LegacyEventDispatcherProxy;
20
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
21
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
22
23
/**
24
 * Class NodeHelper
25
 */
26
class NodeHelper
27
{
28
    /** @var EntityManagerInterface */
29
    private $em;
30
31
    /** @var NodeAdminPublisher */
32
    private $nodeAdminPublisher;
33
34
    /** @var TokenStorageInterface */
35
    private $tokenStorage;
36
37
    /** @var CloneHelper */
38
    private $cloneHelper;
39
40
    /** @var EventDispatcherInterface */
41
    private $eventDispatcher;
42
43
    /**
44
     * NodeHelper constructor.
45
     *
46
     * @param EntityManagerInterface   $em
47
     * @param NodeAdminPublisher       $nodeAdminPublisher
48
     * @param TokenStorageInterface    $tokenStorage
49
     * @param CloneHelper              $cloneHelper
50
     * @param EventDispatcherInterface $eventDispatcher
51 12
     */
52 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...
53
        EntityManagerInterface $em,
54
        NodeAdminPublisher $nodeAdminPublisher,
55
        TokenStorageInterface $tokenStorage,
56
        CloneHelper $cloneHelper,
57
        EventDispatcherInterface $eventDispatcher
58 12
    ) {
59 12
        $this->em = $em;
60 12
        $this->nodeAdminPublisher = $nodeAdminPublisher;
61 12
        $this->tokenStorage = $tokenStorage;
62 12
        $this->cloneHelper = $cloneHelper;
63 12
        $this->eventDispatcher = $eventDispatcher;
64
    }
65
66
    /**
67
     * @param HasNodeInterface $page            The page
68
     * @param NodeTranslation  $nodeTranslation The node translation
69
     * @param NodeVersion      $nodeVersion     The node version
70
     *
71
     * @return NodeVersion
72 1
     */
73
    public function createDraftVersion(
74
        HasNodeInterface $page,
75
        NodeTranslation $nodeTranslation,
76
        NodeVersion $nodeVersion
77 1
    ) {
78 1
        $user = $this->getAdminUser();
79
        $publicPage = $this->cloneHelper->deepCloneAndSave($page);
80
81 1
        /* @var NodeVersion $publicNodeVersion */
82 1
        $publicNodeVersion = $this->em->getRepository(NodeVersion::class)
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...
83 1
            ->createNodeVersionFor(
84
                $publicPage,
85
                $nodeTranslation,
86 1
                $user,
87 1
                $nodeVersion->getOrigin(),
88 1
                NodeVersion::PUBLIC_VERSION,
89
                $nodeVersion->getCreated()
90
            );
91 1
92 1
        $nodeTranslation->setPublicNodeVersion($publicNodeVersion);
93 1
        $nodeVersion->setType(NodeVersion::DRAFT_VERSION);
94 1
        $nodeVersion->setOrigin($publicNodeVersion);
95
        $nodeVersion->setCreated(new \DateTime());
96 1
97 1
        $this->em->persist($nodeTranslation);
98 1
        $this->em->persist($nodeVersion);
99
        $this->em->flush();
100 1
101 1
        $this->dispatch(
102 1
            new NodeEvent(
103 1
                $nodeTranslation->getNode(),
104
                $nodeTranslation,
105
                $nodeVersion,
106
                $page
107
            ),
108
            Events::CREATE_DRAFT_VERSION
109
        );
110 1
111
        return $nodeVersion;
112
    }
113
114
    /**
115
     * @param NodeVersion     $nodeVersion
116
     * @param NodeTranslation $nodeTranslation
117
     * @param int             $nodeVersionTimeout
118
     * @param bool            $nodeVersionIsLocked
119 2
     */
120
    public function prepareNodeVersion(NodeVersion $nodeVersion, NodeTranslation $nodeTranslation, $nodeVersionTimeout, $nodeVersionIsLocked)
121 2
    {
122 2
        $user = $this->getAdminUser();
123 2
        $thresholdDate = date('Y-m-d H:i:s', time() - $nodeVersionTimeout);
124
        $updatedDate = date('Y-m-d H:i:s', strtotime($nodeVersion->getUpdated()->format('Y-m-d H:i:s')));
125 2
126 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...
127 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...
128 1
            if ($nodeVersion === $nodeTranslation->getPublicNodeVersion()) {
129 1
                $this->nodeAdminPublisher
130 1
                    ->createPublicVersion(
131
                        $page,
0 ignored issues
show
Bug introduced by
It seems like $page defined by $nodeVersion->getRef($this->em) on line 127 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...
132
                        $nodeTranslation,
133
                        $nodeVersion,
134
                        $user
135
                    );
136 1
            } else {
137 1
                $this->createDraftVersion(
138
                    $page,
0 ignored issues
show
Bug introduced by
It seems like $page defined by $nodeVersion->getRef($this->em) on line 127 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...
139
                    $nodeTranslation,
140
                    $nodeVersion
141
                );
142
            }
143 2
        }
144
    }
145
146
    /**
147
     * @param Node             $node
148
     * @param NodeTranslation  $nodeTranslation
149
     * @param NodeVersion      $nodeVersion
150
     * @param HasNodeInterface $page
151
     * @param bool             $isStructureNode
152
     * @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...
153
     *
154
     * @return NodeTranslation
155 1
     */
156
    public function updatePage(
157
        Node $node,
158
        NodeTranslation $nodeTranslation,
159
        NodeVersion $nodeVersion,
160
        HasNodeInterface $page,
161
        $isStructureNode,
162
        TabPane $tabPane = null
163 1
    ) {
164 1
        $this->dispatch(
165 1
            new NodeEvent($node, $nodeTranslation, $nodeVersion, $page),
166
            Events::PRE_PERSIST
167
        );
168 1
169 1
        $nodeTranslation->setTitle($page->getTitle());
170
        if ($isStructureNode) {
171
            $nodeTranslation->setSlug('');
172
        }
173 1
174 1
        $nodeVersion->setUpdated(new \DateTime());
175 1
        if ($nodeVersion->getType() == NodeVersion::PUBLIC_VERSION) {
176
            $nodeTranslation->setUpdated($nodeVersion->getUpdated());
177 1
        }
178 1
        $this->em->persist($nodeTranslation);
179 1
        $this->em->persist($nodeVersion);
180 1
        $this->em->persist($node);
181
        if (null !== $tabPane) {
182
            $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...
183 1
        }
184
        $this->em->flush();
185 1
186 1
        $this->dispatch(
187 1
            new NodeEvent($node, $nodeTranslation, $nodeVersion, $page),
188
            Events::POST_PERSIST
189
        );
190 1
191
        return $nodeTranslation;
192
    }
193
194
    /**
195
     * @param string    $refEntityType
196
     * @param string    $pageTitle
197
     * @param string    $locale
198
     * @param Node|null $parentNode
199
     *
200
     * @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...
201 1
     */
202
    public function createPage(
203
        $refEntityType,
204
        $pageTitle,
205
        $locale,
206
        Node $parentNode = null)
207 1
    {
208
        $user = $this->getAdminUser();
209 1
210 1
        $newPage = $this->createNewPage($refEntityType, $pageTitle);
211 1
        if (null !== $parentNode) {
212 1
            $parentNodeTranslation = $parentNode->getNodeTranslation($locale, true);
213 1
            $parentNodeVersion = $parentNodeTranslation->getPublicNodeVersion();
214 1
            $parentPage = $parentNodeVersion->getRef($this->em);
215
            $newPage->setParent($parentPage);
216
        }
217
218 1
        /* @var Node $nodeNewPage */
219 1
        $nodeNewPage = $this->em->getRepository(Node::class)->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...
220 1
        $nodeTranslation = $nodeNewPage->getNodeTranslation($locale, true);
221 1
        if (null !== $parentNode) {
222 1
            $weight = $this->em->getRepository(NodeTranslation::class)->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...
223
                    $parentNode,
224 1
                    $locale
225 1
                ) + 1;
226
            $nodeTranslation->setWeight($weight);
227
        }
228 1
229
        if ($newPage->isStructureNode()) {
230
            $nodeTranslation->setSlug('');
231
        }
232 1
233 1
        $this->em->persist($nodeTranslation);
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $nodeNewPage->getNodeTranslation($locale, true) on line 220 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...
234
        $this->em->flush();
235 1
236
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
237 1
238 1
        $this->dispatch(
239 1
            new NodeEvent($nodeNewPage, $nodeTranslation, $nodeVersion, $newPage),
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $nodeNewPage->getNodeTranslation($locale, true) on line 220 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...
240 1
            Events::ADD_NODE
241
        );
242
243
        return $nodeTranslation;
244 1
    }
245
246
    /**
247
     * @param Node   $node
248
     * @param string $locale
249
     *
250
     * @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...
251
     */
252
    public function deletePage(Node $node, $locale)
253 1
    {
254
        $nodeTranslation = $node->getNodeTranslation($locale, true);
255 1
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
256 1
        $page = $nodeVersion->getRef($this->em);
257 1
258
        $this->dispatch(
259 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 254 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...
260 1
            Events::PRE_DELETE
261 1
        );
262
263
        $node->setDeleted(true);
264 1
        $this->em->persist($node);
265 1
266
        $this->deleteNodeChildren($node, $locale);
267 1
        $this->em->flush();
268 1
269
        $this->dispatch(
270 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 254 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...
271 1
            Events::POST_DELETE
272 1
        );
273
274
        return $nodeTranslation;
275 1
    }
276
277
    /**
278
     * @param Node   $node
279
     * @param string $locale
280
     *
281
     * @return HasNodeInterface
282
     */
283
    public function getPageWithNodeInterface(Node $node, $locale)
284 1
    {
285
        $nodeTranslation = $node->getNodeTranslation($locale, true);
286 1
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
287 1
288
        return $nodeVersion->getRef($this->em);
289 1
    }
290
291
    /**
292
     * @param Node   $node
293
     * @param string $sourceLocale
294
     * @param string $locale
295
     *
296
     * @return NodeTranslation
297
     */
298 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...
299 1
    {
300
        $user = $this->getAdminUser();
301 1
302
        $sourceNodeTranslation = $node->getNodeTranslation($sourceLocale, true);
303 1
        $sourceNodeVersion = $sourceNodeTranslation->getPublicNodeVersion();
304 1
        $sourcePage = $sourceNodeVersion->getRef($this->em);
305 1
        $targetPage = $this->cloneHelper->deepCloneAndSave($sourcePage);
306 1
307
        /* @var NodeTranslation $nodeTranslation */
308
        $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...
309 1
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
310 1
311
        $this->dispatch(
312 1
            new CopyPageTranslationNodeEvent(
313 1
                $node,
314 1
                $nodeTranslation,
315 1
                $nodeVersion,
316
                $targetPage,
317
                $sourceNodeTranslation,
0 ignored issues
show
Bug introduced by
It seems like $sourceNodeTranslation defined by $node->getNodeTranslation($sourceLocale, true) on line 302 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...
318
                $sourceNodeVersion,
319
                $sourcePage,
320
                $sourceLocale
321
            ),
322
            Events::COPY_PAGE_TRANSLATION
323
        );
324
325
        return $nodeTranslation;
326 1
    }
327
328
    /**
329
     * @param Node   $node
330
     * @param string $locale
331
     * @param string $title
332
     *
333
     * @return NodeTranslation|null
334
     */
335
    public function duplicatePage(Node $node, $locale, $title = 'New page')
336 1
    {
337
        $user = $this->getAdminUser();
338 1
339
        $sourceNodeTranslations = $node->getNodeTranslation($locale, true);
340 1
        $sourcePage = $sourceNodeTranslations->getPublicNodeVersion()->getRef($this->em);
341 1
        $targetPage = $this->cloneHelper->deepCloneAndSave($sourcePage);
342 1
        $targetPage->setTitle($title);
343 1
344
        if ($node->getParent()) {
345 1
            $parentNodeTranslation = $node->getParent()->getNodeTranslation($locale, true);
346 1
            $parent = $parentNodeTranslation->getPublicNodeVersion()->getRef($this->em);
347 1
            $targetPage->setParent($parent);
348 1
        }
349
        $this->em->persist($targetPage);
350 1
        $this->em->flush();
351 1
352
        /* @var Node $nodeNewPage */
353
        $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...
354 1
355
        $nodeTranslation = $nodeNewPage->getNodeTranslation($locale, true);
356 1
        if ($targetPage->isStructureNode()) {
357 1
            $nodeTranslation->setSlug('');
358
            $this->em->persist($nodeTranslation);
0 ignored issues
show
Bug introduced by
It seems like $nodeTranslation defined by $nodeNewPage->getNodeTranslation($locale, true) on line 355 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...
359
        }
360
        $this->em->flush();
361 1
362
        return $nodeTranslation;
363 1
    }
364
365
    /**
366
     * @param Node   $node
367
     * @param int    $sourceNodeTranslationId
368
     * @param string $locale
369
     *
370
     * @return NodeTranslation
371
     */
372 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...
373 1
    {
374
        $user = $this->getAdminUser();
375 1
376
        $sourceNodeTranslation = $this->em->getRepository(NodeTranslation::class)->find($sourceNodeTranslationId);
377 1
        $sourceNodeVersion = $sourceNodeTranslation->getPublicNodeVersion();
378 1
        $sourcePage = $sourceNodeVersion->getRef($this->em);
379 1
        $targetPage = $this->cloneHelper->deepCloneAndSave($sourcePage);
380 1
381
        /* @var NodeTranslation $nodeTranslation */
382
        $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...
383 1
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
384 1
385
        $this->dispatch(
386 1
            new RecopyPageTranslationNodeEvent(
387 1
                $node,
388 1
                $nodeTranslation,
389 1
                $nodeVersion,
390
                $targetPage,
391
                $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...
392
                $sourceNodeVersion,
393
                $sourcePage,
394
                $sourceNodeTranslation->getLang()
395
            ),
396 1
            Events::RECOPY_PAGE_TRANSLATION
397
        );
398
399
        return $nodeTranslation;
400 1
    }
401
402
    /**
403
     * @param Node   $node
404
     * @param string $locale
405
     *
406
     * @return NodeTranslation
407
     */
408
    public function createEmptyPage(Node $node, $locale)
409 1
    {
410
        $user = $this->getAdminUser();
411 1
412
        $refEntityName = $node->getRefEntityName();
413 1
        $targetPage = $this->createNewPage($refEntityName);
414 1
415
        /* @var NodeTranslation $nodeTranslation */
416
        $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...
417 1
        $nodeVersion = $nodeTranslation->getPublicNodeVersion();
418 1
419
        $this->dispatch(
420 1
            new NodeEvent($node, $nodeTranslation, $nodeVersion, $targetPage),
421 1
            Events::ADD_EMPTY_PAGE_TRANSLATION
422 1
        );
423
424
        return $nodeTranslation;
425 1
    }
426
427
    /**
428
     * @param string $entityType
429
     * @param string $title
430
     *
431
     * @return HasNodeInterface
432
     */
433
    protected function createNewPage($entityType, $title = 'No title')
434 2
    {
435
        /* @var HasNodeInterface $newPage */
436
        $newPage = new $entityType();
437 2
        $newPage->setTitle($title);
438 2
439
        $this->em->persist($newPage);
440 2
        $this->em->flush();
441 2
442
        return $newPage;
443 2
    }
444
445
    /**
446
     * @param Node   $node
447
     * @param string $locale
448
     */
449 View Code Duplication
    protected function deleteNodeChildren(Node $node, $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...
450 1
    {
451
        $children = $node->getChildren();
452 1
453
        /* @var Node $childNode */
454
        foreach ($children as $childNode) {
455 1
            $childNodeTranslation = $childNode->getNodeTranslation($locale, true);
456 1
            $childNodeVersion = $childNodeTranslation->getPublicNodeVersion();
457 1
            $childNodePage = $childNodeVersion->getRef($this->em);
458 1
459
            $this->dispatch(
460 1
                new NodeEvent(
461 1
                    $childNode,
462 1
                    $childNodeTranslation,
463 1
                    $childNodeVersion,
464
                    $childNodePage
465
                ),
466
                Events::PRE_DELETE
467
            );
468
469
            $childNode->setDeleted(true);
470 1
            $this->em->persist($childNode);
471 1
472
            $this->deleteNodeChildren($childNode, $locale);
473 1
474
            $this->dispatch(
475 1
                new NodeEvent(
476 1
                    $childNode,
477 1
                    $childNodeTranslation,
478 1
                    $childNodeVersion,
479
                    $childNodePage
480
                ),
481
                Events::POST_DELETE
482
            );
483
        }
484
    }
485 1
486
    /**
487
     * @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...
488
     */
489
    protected function getUser()
490 8
    {
491
        $token = $this->tokenStorage->getToken();
492 8
        if ($token) {
493 8
            $user = $token->getUser();
494 8
            if ($user && $user !== 'anon.' && $user instanceof User) {
495 8
                return $user;
496 8
            }
497
        }
498
499
        return null;
500
    }
501
502
    /**
503
     * @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...
504
     */
505
    protected function getAdminUser()
506 8
    {
507
        $user = $this->getUser();
508 8
        if (!$user) {
509 8
            throw new AccessDeniedException('Access denied: User should be an admin user');
510
        }
511
512
        return $user;
513 8
    }
514
515
    /**
516
     * @param object $event
517
     * @param string $eventName
518
     *
519
     * @return object
520
     */
521 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...
522
    {
523
        if (class_exists(LegacyEventDispatcherProxy::class)) {
524
            $eventDispatcher = LegacyEventDispatcherProxy::decorate($this->eventDispatcher);
525
526
            return $eventDispatcher->dispatch($event, $eventName);
527
        }
528
529
        return $this->eventDispatcher->dispatch($eventName, $event);
530
    }
531
}
532