Completed
Pull Request — 5.6 (#2830)
by Jeroen
14:14
created

NodeListener::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Kunstmaan\SeoBundle\EventListener;
4
5
use Doctrine\ORM\EntityManager;
6
use Kunstmaan\AdminBundle\Helper\FormWidgets\FormWidget;
7
use Kunstmaan\AdminBundle\Helper\FormWidgets\Tabs\Tab;
8
use Kunstmaan\NodeBundle\Entity\HasNodeInterface;
9
use Kunstmaan\NodeBundle\Event\AdaptFormEvent;
10
use Kunstmaan\SeoBundle\Entity\Seo;
11
use Kunstmaan\SeoBundle\Form\SeoType;
12
use Kunstmaan\SeoBundle\Form\SocialType;
13
14
/**
15
 * This will add a seo tab on each page
16
 */
17
class NodeListener
18
{
19
    /**
20
     * @var EntityManager
21
     */
22
    private $em;
23
24
    public function __construct(EntityManager $em)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $em. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
25
    {
26
        $this->em = $em;
27
    }
28
29
    public function adaptForm(AdaptFormEvent $event)
30
    {
31
        if ($event->getPage() instanceof HasNodeInterface && !$event->getPage()->isStructureNode()) {
32
            /* @var Seo $seo */
33
            $seo = $this->em->getRepository(Seo::class)->findOrCreateFor($event->getPage());
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 findOrCreateFor() does only exist in the following implementations of said interface: Kunstmaan\SeoBundle\Repository\SeoRepository.

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...
34
35
            $seoWidget = new FormWidget();
36
            $seoWidget->addType('seo', SeoType::class, $seo);
37
            $event->getTabPane()->addTab(new Tab('seo.tab.seo.title', $seoWidget));
38
39
            $socialWidget = new FormWidget();
40
            $socialWidget->addType('social', SocialType::class, $seo);
41
            $socialWidget->setTemplate('@KunstmaanSeo/Admin/Social/social.html.twig');
42
            $event->getTabPane()->addTab(new Tab('seo.tab.social.title', $socialWidget));
43
        }
44
    }
45
}
46