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

Kunstmaan/SeoBundle/EventListener/NodeListener.php (1 issue)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
namespace Kunstmaan\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
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());
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