Completed
Push — master ( 6d6774...64f3ed )
by Jeroen
11:23 queued 05:13
created

PagePartTwigExtension   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 75
Duplicated Lines 17.33 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 6
dl 13
loc 75
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getFunctions() 0 8 1
A renderPageParts() 13 13 1
A getPageParts() 0 7 1
A hasPageParts() 0 4 1

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\PagePartBundle\Twig\Extension;
4
5
use Doctrine\ORM\EntityManager;
6
use Kunstmaan\PagePartBundle\Entity\PagePartRef;
7
use Kunstmaan\PagePartBundle\Helper\HasPagePartsInterface;
8
use Kunstmaan\PagePartBundle\Helper\PagePartInterface;
9
use Kunstmaan\PagePartBundle\Repository\PagePartRefRepository;
10
use Twig\Environment;
11
use Twig\Extension\AbstractExtension;
12
use Twig\TwigFunction;
13
14
/**
15
 * PagePartTwigExtension
16
 *
17
 * @final since 5.4
18
 */
19
class PagePartTwigExtension extends AbstractExtension
20
{
21
    /**
22
     * @var EntityManager
23
     */
24
    protected $em;
25
26
    /**
27
     * @param EntityManager $em
28
     */
29
    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...
30
    {
31
        $this->em = $em;
32
    }
33
34
    /**
35
     * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use TwigFunction[].

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...
36
     */
37
    public function getFunctions()
38
    {
39
        return array(
40
            new TwigFunction('render_pageparts', array($this, 'renderPageParts'), array('needs_environment' => true, 'needs_context' => true, 'is_safe' => array('html'))),
41
            new TwigFunction('getpageparts', array('needs_environment' => true, $this, 'getPageParts')),
42
            new TwigFunction('has_page_parts', [$this, 'hasPageParts']),
43
        );
44
    }
45
46
    /**
47
     * @param Environment           $env
48
     * @param array                 $twigContext The twig context
49
     * @param HasPagePartsInterface $page        The page
50
     * @param string                $contextName The pagepart context
51
     * @param array                 $parameters  Some extra parameters
52
     *
53
     * @return string
54
     */
55 View Code Duplication
    public function renderPageParts(Environment $env, array $twigContext, HasPagePartsInterface $page, $contextName = 'main', array $parameters = array())
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...
56
    {
57
        $template = $env->load('@KunstmaanPagePart/PagePartTwigExtension/widget.html.twig');
58
        /* @var $entityRepository PagePartRefRepository */
59
        $pageparts = $this->getPageParts($page, $contextName);
60
        $newTwigContext = array_merge($parameters, array(
61
            'pageparts' => $pageparts,
62
            'page' => $page,
63
        ));
64
        $newTwigContext = array_merge($newTwigContext, $twigContext);
65
66
        return $template->render($newTwigContext);
67
    }
68
69
    /**
70
     * @param HasPagePartsInterface $page    The page
71
     * @param string                $context The pagepart context
72
     *
73
     * @return PagePartInterface[]
74
     */
75
    public function getPageParts(HasPagePartsInterface $page, $context = 'main')
76
    {
77
        /** @var $entityRepository PagePartRefRepository */
78
        $entityRepository = $this->em->getRepository(PagePartRef::class);
79
80
        return $entityRepository->getPageParts($page, $context);
81
    }
82
83
    /**
84
     * @param HasPagePartsInterface $page
85
     * @param string                $context
86
     *
87
     * @return bool
88
     */
89
    public function hasPageParts(HasPagePartsInterface $page, $context = 'main')
90
    {
91
        return $this->em->getRepository(PagePartRef::class)->hasPageParts($page, $context);
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 hasPageParts() does only exist in the following implementations of said interface: Kunstmaan\PagePartBundle...y\PagePartRefRepository.

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...
92
    }
93
}
94