Completed
Pull Request — master (#325)
by Paul
09:55
created

WidgetMapManager::overwrite()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
rs 9.4285
cc 1
eloc 11
nc 1
nop 3
1
<?php
2
3
namespace Victoire\Bundle\WidgetMapBundle\Manager;
4
5
use Victoire\Bundle\WidgetMapBundle\Helper\WidgetMapHelper;
6
use Doctrine\Orm\EntityManager;
7
use Victoire\Bundle\CoreBundle\Entity\View;
8
use Victoire\Bundle\WidgetBundle\Entity\Widget;
9
use Victoire\Bundle\WidgetMapBundle\Builder\WidgetMapBuilder;
10
use Victoire\Bundle\WidgetMapBundle\Entity\WidgetMap;
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
    /**
186
     * Create a copy of a WidgetMap in "overwrite" mode and insert it in the given view
187
     *
188
     * @param  WidgetMap  $widgetMap
189
     * @param  View       $view
190
     * @return WidgetMap
191
     * @throws \Exception
192
     */
193
    protected function cloneWidgetMap(WidgetMap $widgetMap, View $view)
194
    {
195
        $originalWidgetMap = $widgetMap;
196
        $widgetMap = clone $widgetMap;
197
        $widgetMap->setId(null);
198
        $widgetMap->setAction(WidgetMap::ACTION_OVERWRITE);
199
        $widgetMap->setReplaced($originalWidgetMap);
200
        $originalWidgetMap->addSubstitute($widgetMap);
201
        $view->addWidgetMap($widgetMap);
202
        $this->em->persist($widgetMap);
203
204
        return $widgetMap;
205
    }
206
207
    /**
208
     * Move given WidgetMap as a child of given parent at given position and slot
209
     *
210
     * @param  View      $view
211
     * @param  WidgetMap $widgetMap
212
     * @param  bool      $parent
213
     * @param  bool      $position
214
     * @param  bool      $slot
215
     * @return WidgetMap
216
     */
217
    protected function moveWidgetMap(View $view, WidgetMap $widgetMap, $parent = false, $position = false, $slot = false)
218
    {
219
        if ($widgetMap->getView() !== $view) {
220
            $widgetMap = $this->cloneWidgetMap($widgetMap, $view);
221
        }
222
223
        if ($parent !== false) {
224
            if ($oldParent = $widgetMap->getParent()) {
225
                $oldParent->removeChild($widgetMap);
226
            }
227
            $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...
228
            if ($parent) {
229
                $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...
230
            }
231
        }
232
        if ($position !== false) {
233
            $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...
234
        }
235
        if ($slot !== false) {
236
            $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...
237
        }
238
239
        return $widgetMap;
240
    }
241
242
    /**
243
     * Find return all the given WidgetMap children for each view where it's related
244
     *
245
     * @param  WidgetMap $widgetMap
246
     * @return mixed
247
     */
248
    protected function getChildrenByView(WidgetMap $widgetMap)
249
    {
250
        $beforeChilds = $widgetMap->getChilds(WidgetMap::POSITION_BEFORE);
251
        $afterChilds = $widgetMap->getChilds(WidgetMap::POSITION_AFTER);
252
253
        $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...
254
        $childrenByView['before'] = [];
255
        $childrenByView['after'] = [];
256
        foreach ($beforeChilds as $beforeChild) {
257
            $view = $beforeChild->getView();
258
            $childrenByView['views'][] = $view;
259
            $childrenByView['before'][$view->getId()] = $beforeChild;
260
        }
261
        foreach ($afterChilds as $afterChild) {
262
            $view = $afterChild->getView();
263
            $childrenByView['views'][] = $view;
264
            $childrenByView['after'][$view->getId()] = $afterChild;
265
        }
266
267
        return $childrenByView;
268
    }
269
}
270