Completed
Push — 0.1 ( ecc72d...a8c17f )
by Paweł
46:48
created

MenuItemRepository   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 174
Duplicated Lines 21.84 %

Coupling/Cohesion

Components 2
Dependencies 13

Test Coverage

Coverage 86.81%

Importance

Changes 0
Metric Value
wmc 15
lcom 2
cbo 13
dl 38
loc 174
ccs 79
cts 91
cp 0.8681
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 22 6
A getOneMenuItemByName() 12 12 1
A getOneMenuItemById() 12 12 1
A findChildrenAsTree() 0 14 1
A findRootNodes() 0 11 1
A findChildByParentAndPosition() 14 14 1
A persistAsFirstChildOf() 0 17 1
B persistAsNextSiblingOf() 0 28 3

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
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher Menu Bundle.
7
 *
8
 * Copyright 2016 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2016 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\MenuBundle\Doctrine\ORM;
18
19
use Doctrine\ORM\EntityManager;
20
use Doctrine\ORM\Mapping\ClassMetadata;
21
use Gedmo\Exception\UnexpectedValueException;
22
use Gedmo\Tool\Wrapper\EntityWrapper;
23
use Gedmo\Tree\TreeListener;
24
use SWP\Bundle\MenuBundle\Doctrine\MenuItemRepositoryInterface;
25
use SWP\Bundle\MenuBundle\Model\MenuItemInterface;
26
use SWP\Bundle\StorageBundle\Doctrine\ORM\EntityRepository;
27
use SWP\Component\Common\Pagination\PaginationData;
28
29
class MenuItemRepository extends EntityRepository implements MenuItemRepositoryInterface
30
{
31
    /**
32
     * Tree listener on event manager.
33
     *
34
     * @var TreeListener
35
     */
36
    protected $treeListener;
37
38
    /**
39
     * MenuItemRepository constructor.
40
     *
41
     * @param EntityManager $em
42
     * @param ClassMetadata $class
43
     */
44 83
    public function __construct(EntityManager $em, ClassMetadata $class)
45
    {
46 83
        parent::__construct($em, $class);
47 83
        $treeListener = null;
48 83
        foreach ($em->getEventManager()->getListeners() as $listeners) {
49 83
            foreach ($listeners as $listener) {
50 83
                if ($listener instanceof TreeListener) {
51 83
                    $treeListener = $listener;
52 83
                    break;
53
                }
54
            }
55 83
            if ($treeListener) {
56 83
                break;
57
            }
58
        }
59
60 83
        if (is_null($treeListener)) {
61
            throw new \Gedmo\Exception\InvalidMappingException('Tree listener was not found on your entity manager, it must be hooked into the event manager');
62
        }
63
64 83
        $this->treeListener = $treeListener;
65 83
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70 View Code Duplication
    public function getOneMenuItemByName(string $name)
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...
71
    {
72
        return $this->createQueryBuilder('m')
73
            ->addSelect('c')
74
            ->leftJoin('m.children', 'c')
75
            ->addSelect('ch')
76
            ->leftJoin('c.children', 'ch')
77
            ->where('m.name = :name')
78
            ->setParameter('name', $name)
79
            ->getQuery()
80
            ->getOneOrNullResult();
81
    }
82
83
    /**
84
     * {@inheritdoc}
85
     */
86 11 View Code Duplication
    public function getOneMenuItemById(int $id)
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...
87
    {
88 11
        return $this->createQueryBuilder('m')
89 11
            ->addSelect('c')
90 11
            ->leftJoin('m.children', 'c')
91 11
            ->addSelect('ch')
92 11
            ->leftJoin('c.children', 'ch')
93 11
            ->where('m.id = :id')
94 11
            ->setParameter('id', $id)
95 11
            ->getQuery()
96 11
            ->getOneOrNullResult();
97
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102 3
    public function findChildrenAsTree(MenuItemInterface $menuItem)
103
    {
104 3
        $queryBuilder = $this->createQueryBuilder('m');
105
        $queryBuilder
106 3
            ->addSelect('children')
107 3
            ->leftJoin('m.children', 'children')
108 3
            ->where('m.parent = :parent')
109 3
            ->addOrderBy('m.root')
110 3
            ->setParameter('parent', $menuItem)
111 3
            ->orderBy('m.lft', 'asc')
112
        ;
113
114 3
        return $this->getPaginator($queryBuilder, new PaginationData());
115
    }
116
117
    /**
118
     * {@inheritdoc}
119
     */
120 2
    public function findRootNodes()
121
    {
122 2
        $queryBuilder = $this->createQueryBuilder('m');
123
        $queryBuilder
124 2
            ->addSelect('children')
125 2
            ->leftJoin('m.children', 'children')
126 2
            ->where($queryBuilder->expr()->isNull('m.parent'))
127 2
            ->orderBy('m.id', 'asc');
128
129 2
        return $this->getPaginator($queryBuilder, new PaginationData());
130
    }
131
132
    /**
133
     * {@inheritdoc}
134
     */
135 3 View Code Duplication
    public function findChildByParentAndPosition(MenuItemInterface $parent, int $position)
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...
136
    {
137 3
        return $this->createQueryBuilder('m')
138 3
            ->addSelect('c')
139 3
            ->leftJoin('m.children', 'c')
140 3
            ->where('m.parent = :id')
141 3
            ->andWhere('m.position = :position')
142 3
            ->setParameters([
143 3
                'id' => $parent->getId(),
144 3
                'position' => $position,
145
            ])
146 3
            ->getQuery()
147 3
            ->getOneOrNullResult();
148
    }
149
150
    /**
151
     * {@inheritdoc}
152
     */
153 1
    public function persistAsFirstChildOf(MenuItemInterface $node, MenuItemInterface $parent)
154
    {
155 1
        $wrapped = new EntityWrapper($node, $this->_em);
156 1
        $meta = $this->getClassMetadata();
157 1
        $config = $this->treeListener->getConfiguration($this->_em, $meta->name);
158
159 1
        $wrapped->setPropertyValue($config['parent'], $parent);
160
161 1
        $wrapped->setPropertyValue($config['left'], 0);
162 1
        $oid = spl_object_hash($node);
163 1
        $this->treeListener
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Gedmo\Tree\Strategy as the method setNodePosition() does only exist in the following implementations of said interface: Gedmo\Tree\Strategy\ORM\Nested.

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...
164 1
            ->getStrategy($this->_em, $meta->name)
165 1
            ->setNodePosition($oid, 'FirstChild')
166
        ;
167
168 1
        $this->_em->persist($node);
169 1
    }
170
171
    /**
172
     * {@inheritdoc}
173
     */
174 2
    public function persistAsNextSiblingOf(MenuItemInterface $node, MenuItemInterface $sibling)
175
    {
176 2
        $wrapped = new EntityWrapper($node, $this->_em);
177 2
        $meta = $this->getClassMetadata();
178 2
        $config = $this->treeListener->getConfiguration($this->_em, $meta->name);
179
180 2
        $wrappedSibling = new EntityWrapper($sibling, $this->_em);
181 2
        $newParent = $wrappedSibling->getPropertyValue($config['parent']);
182 2
        if (null === $newParent && isset($config['root'])) {
183
            throw new UnexpectedValueException('Cannot persist sibling for a root node, tree operation is not possible');
184
        }
185
186 2
        $node->sibling = $sibling;
0 ignored issues
show
Bug introduced by
Accessing sibling on the interface SWP\Bundle\MenuBundle\Model\MenuItemInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
187 2
        $sibling = $newParent;
188
189 2
        $wrapped->setPropertyValue($config['parent'], $sibling);
190
191 2
        $wrapped->setPropertyValue($config['left'], 0);
192 2
        $oid = spl_object_hash($node);
193 2
        $this->treeListener
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Gedmo\Tree\Strategy as the method setNodePosition() does only exist in the following implementations of said interface: Gedmo\Tree\Strategy\ORM\Nested.

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...
194 2
            ->getStrategy($this->_em, $meta->name)
195 2
            ->setNodePosition($oid, 'NextSibling')
196
        ;
197
198 2
        $this->_em->persist($node);
199
200 2
        return $this;
201
    }
202
}
203