Completed
Pull Request — master (#338)
by Leny
06:17
created

WidgetMapManager::moveWidgetMap()   C

Complexity

Conditions 7
Paths 40

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 10
Bugs 1 Features 0
Metric Value
c 10
b 1
f 0
dl 0
loc 24
rs 6.7272
cc 7
eloc 14
nc 40
nop 5
1
<?php
2
3
namespace Victoire\Bundle\WidgetMapBundle\Manager;
4
5
use Doctrine\Orm\EntityManager;
6
use Victoire\Bundle\CoreBundle\Entity\View;
7
use Victoire\Bundle\WidgetBundle\Entity\Widget;
8
use Victoire\Bundle\WidgetMapBundle\Builder\WidgetMapBuilder;
9
use Victoire\Bundle\WidgetMapBundle\Entity\WidgetMap;
10
use Victoire\Bundle\WidgetMapBundle\Helper\WidgetMapHelper;
11
12
class WidgetMapManager
13
{
14
    private $em;
15
    private $builder;
16
17
    public function __construct(EntityManager $em, WidgetMapBuilder $builder)
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...
18
    {
19
        $this->em = $em;
20
        $this->builder = $builder;
21
    }
22
23
    /**
24
     * Insert a WidgetMap in a view at given position.
25
     *
26
     * @param string $slotId
27
     */
28
    public function insert(Widget $widget, View $view, $slotId, $position, $widgetReference)
29
    {
30
        $parent = null;
31
        if ($widgetReference) {
32
            $parent = $this->em->getRepository('VictoireWidgetMapBundle:WidgetMap')->find($widgetReference);
33
        }
34
        //create the new widget map
35
        $widgetMapEntry = new WidgetMap();
36
        $widgetMapEntry->setAction(WidgetMap::ACTION_CREATE);
37
        $widgetMapEntry->setWidget($widget);
38
        $widgetMapEntry->setSlot($slotId);
39
        $widgetMapEntry->setPosition($position);
40
        $widgetMapEntry->setParent($parent);
0 ignored issues
show
Bug introduced by
It seems like $parent defined by $this->em->getRepository...>find($widgetReference) on line 32 can also be of type object; however, Victoire\Bundle\WidgetMa...\WidgetMap::setParent() does only seem to accept null|object<Victoire\Bun...undle\Entity\WidgetMap>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
41
42
        $view->addWidgetMap($widgetMapEntry);
43
    }
44
45
    /**
46
     * moves a widget in a view.
47
     *
48
     * @param View  $view
49
     * @param array $sortedWidget
50
     *
51
     * @return void
52
     */
53
    public function move(View $view, $sortedWidget)
54
    {
55
        /** @var WidgetMap $parentWidgetMap */
56
        $parentWidgetMap = $this->em->getRepository('VictoireWidgetMapBundle:WidgetMap')->find((int) $sortedWidget['parentWidgetMap']);
57
        $position = $sortedWidget['position'];
58
        $slot = $sortedWidget['slot'];
59
        /** @var WidgetMap $widgetMap */
60
        $widgetMap = $this->em->getRepository('VictoireWidgetMapBundle:WidgetMap')->find((int) $sortedWidget['widgetMap']);
61
62
        $originalParent = $widgetMap->getParent();
63
        $originalPosition = $widgetMap->getPosition();
64
65
        $children = $widgetMap->getChildren($view);
66
        $beforeChild = !empty($children[WidgetMap::POSITION_BEFORE]) ? $children[WidgetMap::POSITION_BEFORE] : null;
67
        $afterChild = !empty($children[WidgetMap::POSITION_AFTER]) ? $children[WidgetMap::POSITION_AFTER] : null;
68
69
        $parentWidgetMapChildren = $this->getChildrenByView($parentWidgetMap);
70
71
        $widgetMap = $this->moveWidgetMap($view, $widgetMap, $parentWidgetMap, $position, $slot);
0 ignored issues
show
Documentation introduced by
$parentWidgetMap is of type object<Victoire\Bundle\W...undle\Entity\WidgetMap>, but the function expects a boolean.

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...
72
73
        // If the moved widgetMap has someone at both his before and after, arbitrary move UP the before side
74
        // and find the first place after the before widgetMap hierarchy to place the after widgetMap.
75
        $this->moveChildren($view, $beforeChild, $afterChild, $originalParent, $originalPosition);
76
77
        foreach ($parentWidgetMapChildren['views'] as $_view) {
78
            if ($_view->getId() !== $view->getId()) {
79 View Code Duplication
                if (isset($parentWidgetMapChildren['before'][$_view->getId()])) {
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...
80
                    $parentWidgetMapChildren['before'][$_view->getId()]->setParent($widgetMap);
81
                }
82 View Code Duplication
                if (isset($parentWidgetMapChildren['after'][$_view->getId()])) {
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...
83
                    $parentWidgetMapChildren['after'][$_view->getId()]->setParent($widgetMap);
84
                }
85
            }
86
        }
87
    }
88
89
    /**
90
     * Delete the widget from the view.
91
     *
92
     * @param View   $view
93
     * @param Widget $widget
94
     *
95
     * @throws \Exception Widget map does not exists
96
     */
97
    public function delete(View $view, Widget $widget)
98
    {
99
        $this->builder->build($view);
100
101
        $widgetMap = WidgetMapHelper::getWidgetMapByWidgetAndView($widget, $view);
102
        $slot = $widgetMap->getSlot();
103
104
        $originalParent = $widgetMap->getParent();
105
        $originalPosition = $widgetMap->getPosition();
106
107
        $children = $widgetMap->getChildren($view);
108
        $beforeChild = !empty($children[WidgetMap::POSITION_BEFORE]) ? $children[WidgetMap::POSITION_BEFORE] : null;
109
        $afterChild = !empty($children[WidgetMap::POSITION_AFTER]) ? $children[WidgetMap::POSITION_AFTER] : null;
110
111
        //we remove the widget from the current view
112
        if ($widgetMap->getView() === $view) {
113
            //remove the widget map from the slot
114
            $view->removeWidgetMap($widgetMap);
115
        } else {
116
            //the widget is owned by another view (a parent)
117
            //so we add a new widget map that indicates we delete this widget
118
            $replaceWidgetMap = new WidgetMap();
119
            $replaceWidgetMap->setAction(WidgetMap::ACTION_DELETE);
120
            $replaceWidgetMap->setWidget($widget);
121
            $replaceWidgetMap->setSlot($slot);
122
            $replaceWidgetMap->setReplaced($widgetMap);
123
124
            $view->addWidgetMap($replaceWidgetMap);
125
        }
126
127
        $this->moveChildren($view, $beforeChild, $afterChild, $originalParent, $originalPosition);
128
    }
129
130
    /**
131
     * the widget is owned by another view (a parent)
132
     * so we add a new widget map that indicates we delete this widget.
133
     *
134
     * @param View      $view
135
     * @param WidgetMap $originalWidgetMap
136
     * @param Widget    $widgetCopy
137
     *
138
     * @throws \Exception
139
     */
140
    public function overwrite(View $view, WidgetMap $originalWidgetMap, Widget $widgetCopy)
141
    {
142
        $widgetMap = new WidgetMap();
143
        $widgetMap->setAction(WidgetMap::ACTION_OVERWRITE);
144
        $widgetMap->setReplaced($originalWidgetMap);
145
        $widgetMap->setWidget($widgetCopy);
146
        $widgetMap->setView($view);
147
        $widgetMap->setSlot($originalWidgetMap->getSlot());
148
        $widgetMap->setPosition($originalWidgetMap->getPosition());
149
        $widgetMap->setAsynchronous($widgetCopy->isAsynchronous());
150
        $widgetMap->setParent($originalWidgetMap->getParent());
151
152
        $view->addWidgetMap($widgetMap);
153
    }
154
155
    /**
156
     * If the moved widgetMap has someone at both his before and after, arbitrary move UP the before side
157
     * and find the first place after the before widgetMap hierarchy to place the after widgetMap.
158
     *
159
     * @param View $view
160
     * @param $beforeChild
161
     * @param $afterChild
162
     * @param $originalParent
163
     * @param $originalPosition
164
     */
165
    public function moveChildren(View $view, $beforeChild, $afterChild, $originalParent, $originalPosition)
166
    {
167
        if ($beforeChild && $afterChild) {
168
            $this->moveWidgetMap($view, $beforeChild, $originalParent, $originalPosition);
169
170
            $child = $beforeChild;
171
            while ($child->getChild(WidgetMap::POSITION_AFTER)) {
172
                $child = $child->getChild(WidgetMap::POSITION_AFTER);
173
            }
174
            if ($afterChild->getId() !== $child->getId()) {
175
                $this->moveWidgetMap($view, $afterChild, $child);
176
            }
177
        } elseif ($beforeChild) {
178
            $this->moveWidgetMap($view, $beforeChild, $originalParent, $originalPosition);
179
        } elseif ($afterChild) {
180
            $this->moveWidgetMap($view, $afterChild, $originalParent, $originalPosition);
181
        }
182
    }
183
184
    /**
185
     * Create a copy of a WidgetMap in "overwrite" mode and insert it in the given view.
186
     *
187
     * @param WidgetMap $widgetMap
188
     * @param View      $view
189
     *
190
     * @throws \Exception
191
     *
192
     * @return WidgetMap
193
     */
194
    protected function cloneWidgetMap(WidgetMap $widgetMap, View $view)
195
    {
196
        $originalWidgetMap = $widgetMap;
197
        $widgetMap = clone $widgetMap;
198
        $widgetMap->setId(null);
199
        $widgetMap->setAction(WidgetMap::ACTION_OVERWRITE);
200
        $widgetMap->setReplaced($originalWidgetMap);
201
        $originalWidgetMap->addSubstitute($widgetMap);
202
        $view->addWidgetMap($widgetMap);
203
        $this->em->persist($widgetMap);
204
205
        return $widgetMap;
206
    }
207
208
    /**
209
     * Move given WidgetMap as a child of given parent at given position and slot.
210
     *
211
     * @param View      $view
212
     * @param WidgetMap $widgetMap
213
     * @param bool      $parent
214
     * @param bool      $position
215
     * @param bool      $slot
216
     *
217
     * @return WidgetMap
218
     */
219
    protected function moveWidgetMap(View $view, WidgetMap $widgetMap, $parent = false, $position = false, $slot = false)
220
    {
221
        if ($widgetMap->getView() !== $view) {
222
            $widgetMap = $this->cloneWidgetMap($widgetMap, $view);
223
        }
224
225
        if ($parent !== false) {
226
            if ($oldParent = $widgetMap->getParent()) {
227
                $oldParent->removeChild($widgetMap);
228
            }
229
            $widgetMap->setParent($parent);
0 ignored issues
show
Documentation introduced by
$parent is of type boolean, but the function expects a null|object<Victoire\Bun...undle\Entity\WidgetMap>.

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...
230
            if ($parent) {
231
                $parent->addChild($widgetMap);
0 ignored issues
show
Bug introduced by
The method addChild cannot be called on $parent (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
232
            }
233
        }
234
        if ($position !== false) {
235
            $widgetMap->setPosition($position);
0 ignored issues
show
Documentation introduced by
$position is of type boolean, but the function expects a string.

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...
236
        }
237
        if ($slot !== false) {
238
            $widgetMap->setSlot($slot);
0 ignored issues
show
Documentation introduced by
$slot is of type boolean, but the function expects a string.

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...
239
        }
240
241
        return $widgetMap;
242
    }
243
244
    /**
245
     * Find return all the given WidgetMap children for each view where it's related.
246
     *
247
     * @param WidgetMap $widgetMap
248
     *
249
     * @return mixed
250
     */
251
    protected function getChildrenByView(WidgetMap $widgetMap)
252
    {
253
        $beforeChilds = $widgetMap->getChilds(WidgetMap::POSITION_BEFORE);
254
        $afterChilds = $widgetMap->getChilds(WidgetMap::POSITION_AFTER);
255
256
        $childrenByView['views'] = [];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$childrenByView was never initialized. Although not strictly required by PHP, it is generally a good practice to add $childrenByView = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
257
        $childrenByView['before'] = [];
258
        $childrenByView['after'] = [];
259
        foreach ($beforeChilds as $beforeChild) {
260
            $view = $beforeChild->getView();
261
            $childrenByView['views'][] = $view;
262
            $childrenByView['before'][$view->getId()] = $beforeChild;
263
        }
264
        foreach ($afterChilds as $afterChild) {
265
            $view = $afterChild->getView();
266
            $childrenByView['views'][] = $view;
267
            $childrenByView['after'][$view->getId()] = $afterChild;
268
        }
269
270
        return $childrenByView;
271
    }
272
}
273