Completed
Pull Request — master (#375)
by Paul
06:22
created

WidgetMapManager::insert()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 28
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 28
rs 8.8571
cc 3
eloc 20
nc 3
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
        $quantum = $this->em->getRepository('VictoireWidgetMapBundle:WidgetMap')->findOneBy([
31
           'view' => $view,
32
           'slot' => $slotId,
33
           'position' => $position,
34
           'parent' => $widgetReference,
35
        ]);
36
        if ($quantum) {
37
            $widget->setWidgetMap($quantum);
38
            $view->addWidgetMap($quantum);
39
        } else {
40
41
            $parent = null;
42
            if ($widgetReference) {
43
                $parent = $this->em->getRepository('VictoireWidgetMapBundle:WidgetMap')->find($widgetReference);
44
            }
45
            //create the new widget map
46
            $widgetMapEntry = new WidgetMap();
47
            $widgetMapEntry->setAction(WidgetMap::ACTION_CREATE);
48
            $widgetMapEntry->setSlot($slotId);
49
            $widgetMapEntry->setPosition($position);
50
            $widgetMapEntry->setParent($parent);
0 ignored issues
show
Bug introduced by
It seems like $parent defined by $this->em->getRepository...>find($widgetReference) on line 43 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...
51
            $widget->setWidgetMap($widgetMapEntry);
52
53
            $view->addWidgetMap($widgetMapEntry);
54
        }
55
    }
56
57
    /**
58
     * moves a widget in a view.
59
     *
60
     * @param View  $view
61
     * @param array $sortedWidget
62
     *
63
     * @return void
64
     */
65
    public function move(View $view, $sortedWidget)
66
    {
67
        /** @var WidgetMap $parentWidgetMap */
68
        $parentWidgetMap = $this->em->getRepository('VictoireWidgetMapBundle:WidgetMap')->find((int) $sortedWidget['parentWidgetMap']);
69
        $position = $sortedWidget['position'];
70
        $slot = $sortedWidget['slot'];
71
        /** @var WidgetMap $widgetMap */
72
        $widgetMap = $this->em->getRepository('VictoireWidgetMapBundle:WidgetMap')->find((int) $sortedWidget['widgetMap']);
73
74
        $originalParent = $widgetMap->getParent();
75
        $originalPosition = $widgetMap->getPosition();
76
77
        $children = $widgetMap->getChildren($view);
78
        $beforeChild = !empty($children[WidgetMap::POSITION_BEFORE]) ? $children[WidgetMap::POSITION_BEFORE] : null;
79
        $afterChild = !empty($children[WidgetMap::POSITION_AFTER]) ? $children[WidgetMap::POSITION_AFTER] : null;
80
81
        $parentWidgetMapChildren = $this->getChildrenByView($parentWidgetMap);
82
83
        $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...
84
85
        // If the moved widgetMap has someone at both his before and after, arbitrary move UP the before side
86
        // and find the first place after the before widgetMap hierarchy to place the after widgetMap.
87
        $this->moveChildren($view, $beforeChild, $afterChild, $originalParent, $originalPosition);
88
89
        foreach ($parentWidgetMapChildren['views'] as $_view) {
90
            if ($_view->getId() !== $view->getId()) {
91 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...
92
                    $parentWidgetMapChildren['before'][$_view->getId()]->setParent($widgetMap);
93
                }
94 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...
95
                    $parentWidgetMapChildren['after'][$_view->getId()]->setParent($widgetMap);
96
                }
97
            }
98
        }
99
    }
100
101
    /**
102
     * Delete the widget from the view.
103
     *
104
     * @param View   $view
105
     * @param Widget $widget
106
     *
107
     * @throws \Exception Widget map does not exists
108
     */
109
    public function delete(View $view, Widget $widget)
110
    {
111
        $this->builder->build($view);
112
113
        $widgetMap = WidgetMapHelper::getWidgetMapByWidgetAndView($widget, $view);
114
        $slot = $widgetMap->getSlot();
115
116
        $originalParent = $widgetMap->getParent();
117
        $originalPosition = $widgetMap->getPosition();
118
119
        $children = $widgetMap->getChildren($view);
120
        $beforeChild = !empty($children[WidgetMap::POSITION_BEFORE]) ? $children[WidgetMap::POSITION_BEFORE] : null;
121
        $afterChild = !empty($children[WidgetMap::POSITION_AFTER]) ? $children[WidgetMap::POSITION_AFTER] : null;
122
123
        //we remove the widget from the current view
124
        if ($widgetMap->getView() === $view) {
125
            //remove the widget map from the slot
126
            $view->removeWidgetMap($widgetMap);
127
        } else {
128
            //the widget is owned by another view (a parent)
129
            //so we add a new widget map that indicates we delete this widget
130
            $replaceWidgetMap = new WidgetMap();
131
            $replaceWidgetMap->setAction(WidgetMap::ACTION_DELETE);
132
            $replaceWidgetMap->setWidget($widget);
0 ignored issues
show
Deprecated Code introduced by
The method Victoire\Bundle\WidgetMa...\WidgetMap::setWidget() has been deprecated.

This method has been deprecated.

Loading history...
133
            $replaceWidgetMap->setSlot($slot);
134
            $replaceWidgetMap->setReplaced($widgetMap);
135
136
            $view->addWidgetMap($replaceWidgetMap);
137
        }
138
139
        $this->moveChildren($view, $beforeChild, $afterChild, $originalParent, $originalPosition);
140
    }
141
142
    /**
143
     * the widget is owned by another view (a parent)
144
     * so we add a new widget map that indicates we delete this widget.
145
     *
146
     * @param View      $view
147
     * @param WidgetMap $originalWidgetMap
148
     * @param Widget    $widgetCopy
149
     *
150
     * @throws \Exception
151
     */
152
    public function overwrite(View $view, WidgetMap $originalWidgetMap, Widget $widgetCopy)
153
    {
154
        $widgetMap = new WidgetMap();
155
        $widgetMap->setAction(WidgetMap::ACTION_OVERWRITE);
156
        $widgetMap->setReplaced($originalWidgetMap);
157
        $widgetMap->setWidget($widgetCopy);
0 ignored issues
show
Deprecated Code introduced by
The method Victoire\Bundle\WidgetMa...\WidgetMap::setWidget() has been deprecated.

This method has been deprecated.

Loading history...
158
        $widgetMap->setView($view);
159
        $widgetMap->setSlot($originalWidgetMap->getSlot());
160
        $widgetMap->setPosition($originalWidgetMap->getPosition());
161
        $widgetMap->setAsynchronous($widgetCopy->isAsynchronous());
162
        $widgetMap->setParent($originalWidgetMap->getParent());
163
164
        $view->addWidgetMap($widgetMap);
165
    }
166
167
    /**
168
     * If the moved widgetMap has someone at both his before and after, arbitrary move UP the before side
169
     * and find the first place after the before widgetMap hierarchy to place the after widgetMap.
170
     *
171
     * @param View $view
172
     * @param $beforeChild
173
     * @param $afterChild
174
     * @param $originalParent
175
     * @param $originalPosition
176
     */
177
    public function moveChildren(View $view, $beforeChild, $afterChild, $originalParent, $originalPosition)
178
    {
179
        if ($beforeChild && $afterChild) {
180
            $this->moveWidgetMap($view, $beforeChild, $originalParent, $originalPosition);
181
182
            $child = $beforeChild;
183
            while ($child->getChild(WidgetMap::POSITION_AFTER)) {
184
                $child = $child->getChild(WidgetMap::POSITION_AFTER);
185
            }
186
            if ($afterChild->getId() !== $child->getId()) {
187
                $this->moveWidgetMap($view, $afterChild, $child);
188
            }
189
        } elseif ($beforeChild) {
190
            $this->moveWidgetMap($view, $beforeChild, $originalParent, $originalPosition);
191
        } elseif ($afterChild) {
192
            $this->moveWidgetMap($view, $afterChild, $originalParent, $originalPosition);
193
        }
194
    }
195
196
    /**
197
     * Create a copy of a WidgetMap in "overwrite" mode and insert it in the given view.
198
     *
199
     * @param WidgetMap $widgetMap
200
     * @param View      $view
201
     *
202
     * @throws \Exception
203
     *
204
     * @return WidgetMap
205
     */
206
    protected function cloneWidgetMap(WidgetMap $widgetMap, View $view)
207
    {
208
        $originalWidgetMap = $widgetMap;
209
        $widgetMap = clone $widgetMap;
210
        $widgetMap->setId(null);
211
        $widgetMap->setAction(WidgetMap::ACTION_OVERWRITE);
212
        $widgetMap->setReplaced($originalWidgetMap);
213
        $originalWidgetMap->addSubstitute($widgetMap);
214
        $widgetMap->setView($view);
215
        $view->addWidgetMap($widgetMap);
216
        $this->em->persist($widgetMap);
217
218
        return $widgetMap;
219
    }
220
221
    /**
222
     * Move given WidgetMap as a child of given parent at given position and slot.
223
     *
224
     * @param View      $view
225
     * @param WidgetMap $widgetMap
226
     * @param bool      $parent
227
     * @param bool      $position
228
     * @param bool      $slot
229
     *
230
     * @return WidgetMap
231
     */
232
    protected function moveWidgetMap(View $view, WidgetMap $widgetMap, $parent = false, $position = false, $slot = false)
233
    {
234
        if ($widgetMap->getView() !== $view) {
235
            $widgetMap = $this->cloneWidgetMap($widgetMap, $view);
236
        }
237
238
        if ($parent !== false) {
239
            if ($oldParent = $widgetMap->getParent()) {
240
                $oldParent->removeChild($widgetMap);
241
            }
242
            $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...
243
            if ($parent) {
244
                $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...
245
            }
246
        }
247
        if ($position !== false) {
248
            $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...
249
        }
250
        if ($slot !== false) {
251
            $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...
252
        }
253
254
        return $widgetMap;
255
    }
256
257
    /**
258
     * Find return all the given WidgetMap children for each view where it's related.
259
     *
260
     * @param WidgetMap $widgetMap
261
     *
262
     * @return mixed
263
     */
264
    protected function getChildrenByView(WidgetMap $widgetMap)
265
    {
266
        $beforeChilds = $widgetMap->getChilds(WidgetMap::POSITION_BEFORE);
267
        $afterChilds = $widgetMap->getChilds(WidgetMap::POSITION_AFTER);
268
269
        $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...
270
        $childrenByView['before'] = [];
271
        $childrenByView['after'] = [];
272
        foreach ($beforeChilds as $beforeChild) {
273
            $view = $beforeChild->getView();
274
            $childrenByView['views'][] = $view;
275
            $childrenByView['before'][$view->getId()] = $beforeChild;
276
        }
277
        foreach ($afterChilds as $afterChild) {
278
            $view = $afterChild->getView();
279
            $childrenByView['views'][] = $view;
280
            $childrenByView['after'][$view->getId()] = $afterChild;
281
        }
282
283
        return $childrenByView;
284
    }
285
}
286