Completed
Push — master ( 076dd2...15dd43 )
by Gaetano
11:40
created

LocationManager::update()   F

Complexity

Conditions 22
Paths 259

Size

Total Lines 84
Code Lines 42

Duplication

Lines 10
Ratio 11.9 %

Importance

Changes 8
Bugs 2 Features 2
Metric Value
cc 22
eloc 42
c 8
b 2
f 2
nc 259
nop 0
dl 10
loc 84
rs 3.7039

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use eZ\Publish\API\Repository\Values\Content\Location;
6
use Kaliop\eZMigrationBundle\API\Collection\ContentCollection;
7
use Kaliop\eZMigrationBundle\API\Collection\LocationCollection;
8
use Kaliop\eZMigrationBundle\Core\Matcher\ContentMatcher;
9
use Kaliop\eZMigrationBundle\Core\Matcher\LocationMatcher;
10
11
class LocationManager extends RepositoryExecutor
12
{
13
    protected $supportedStepTypes = array('location');
14
15
    protected $contentMatcher;
16
    protected $locationMatcher;
17
18
    public function __construct(ContentMatcher $contentMatcher, LocationMatcher $locationMatcher)
19
    {
20
        $this->contentMatcher = $contentMatcher;
21
        $this->locationMatcher = $locationMatcher;
22
    }
23
24
    /**
25
     * Method to handle the create operation of the migration instructions
26
     */
27
    protected function create()
28
    {
29
        $locationService = $this->repository->getLocationService();
30
31
        if (!isset($this->dsl['parent_location_id'])) {
32
            throw new \Exception('Missing parent location id. This is required to create the new location.');
33
        }
34
        if (!is_array($this->dsl['parent_location_id'])) {
35
            $this->dsl['parent_location_id'] = array($this->dsl['parent_location_id']);
36
        }
37
        foreach ($this->dsl['parent_location_id'] as $id => $parentLocationId) {
38
            if ($this->referenceResolver->isReference($parentLocationId)) {
39
                $this->dsl['parent_location_id'][$id] = $this->referenceResolver->getReferenceValue($parentLocationId);
40
            }
41
        }
42
43
        $contentCollection = $this->matchContents('create');
44
45
        $locations = null;
46
        foreach ($contentCollection as $content) {
0 ignored issues
show
Bug introduced by
The expression $contentCollection of type object<Kaliop\eZMigratio...ContentCollection>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
47
            $contentInfo = $content->contentInfo;
48
49
            foreach ($this->dsl['parent_location_id'] as $parentLocationId) {
0 ignored issues
show
Bug introduced by
The expression $this->dsl['parent_location_id'] of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
50
                $locationCreateStruct = $locationService->newLocationCreateStruct($parentLocationId);
51
52
                $locationCreateStruct->hidden = isset($this->dsl['is_hidden']) ?: false;
53
54
                if (isset($this->dsl['priority'])) {
55
                    $locationCreateStruct->priority = $this->dsl['priority'];
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->dsl['priority'] of type array is incompatible with the declared type integer of property $priority.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
56
                }
57
58
                $locationCreateStruct->sortOrder = $this->getSortOrder();
59
                $locationCreateStruct->sortField = $this->getSortField();
60
61
                $locations[] = $locationService->createLocation($contentInfo, $locationCreateStruct);
62
            }
63
        }
64
65
        $this->setReferences(new LocationCollection($locations));
0 ignored issues
show
Documentation introduced by
$locations is of type null, but the function expects a array.

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...
66
    }
67
68
    /**
69
     * Updates basic information for a location like priority, sort field and sort order.
70
     * Updates the visibility of the location when needed.
71
     * Can move a location and its children to a new parent location or swap two locations.
72
     *
73
     * @todo add support for flexible matchers
74
     */
75
    protected function update()
76
    {
77
        $locationService = $this->repository->getLocationService();
78
79
        $locationCollection = $this->matchLocations('update');
80
81
        if (count($locationCollection) > 1 && array_key_exists('references', $this->dsl)) {
82
            throw new \Exception("Can not execute Location update because multiple contents match, and a references section is specified in the dsl. References can be set when only 1 content matches");
83
        }
84
85
        if (count($locationCollection) > 1 && array_key_exists('swap_with_location', $this->dsl)) {
86
            throw new \Exception("Can not execute Location update because multiple contents match, and a swap_with_location is specified in the dsl. References can be set when only 1 content matches");
87
        }
88
89
        if (isset($this->dsl['swap_with_location']) && isset($this->dsl['parent_location_id'])) {
90
            throw new \Exception('Cannot move location to a new parent and swap location with another location at the same time.');
91
        }
92
93
        /*$locationId = $this->dsl['location_id'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
94
        if ($this->referenceResolver->isReference($locationId)) {
95
            $locationId = $this->referenceResolver->getReferenceValue($locationId);
96
        }*/
97
98
        foreach ($locationCollection as $location) {
0 ignored issues
show
Bug introduced by
The expression $locationCollection of type object<Kaliop\eZMigratio...ocationCollection>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
99
            //$location = $locationService->loadLocation($locationId);
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
100
101
            if (array_key_exists('priority', $this->dsl)
102
                || array_key_exists('sort_field', $this->dsl)
103
                || array_key_exists('sort_order', $this->dsl)
104
                || array_key_exists('remote_id', $this->dsl)
105
            ) {
106
                $locationUpdateStruct = $locationService->newLocationUpdateStruct();
107
108
                    if (isset($this->dsl['priority'])) {
109
                        $locationUpdateStruct->priority = $this->dsl['priority'];
110
                    }
111
112
                    if (isset($this->dsl['sort_field'])) {
113
                        $locationUpdateStruct->sortField = $this->getSortField($location->sortField);
114
                    }
115
116
                    if (isset($this->dsl['sort_order'])) {
117
                        $locationUpdateStruct->sortOrder = $this->getSortOrder($location->sortOrder);
118
                    }
119
120
                    if (isset($this->dsl['remote_id'])) {
121
                        $locationUpdateStruct->remoteId = $this->dsl['remote_id'];
122
                    }
123
124
                $locationService->updateLocation($location, $locationUpdateStruct);
125
            }
126
127
            // Check if visibility needs to be updated
128
            if (isset($this->dsl['is_hidden'])) {
129
                if ($this->dsl['is_hidden']) {
130
                    $locationService->hideLocation($location);
131
                } else {
132
                    $locationService->unhideLocation($location);
133
                }
134
            }
135
136
            // Move or swap location
137
            if (isset($this->dsl['parent_location_id'])) {
138
                // Move the location and all it's children to a new parent
139
                $parentLocationId = $this->dsl['parent_location_id'];
140
                if ($this->referenceResolver->isReference($parentLocationId)) {
141
                    $parentLocationId = $this->referenceResolver->getReferenceValue($parentLocationId);
142
                }
143
                $newParentLocation = $locationService->loadLocation($parentLocationId);
144
                $locationService->moveSubtree($location, $newParentLocation);
145 View Code Duplication
            } elseif (isset($this->dsl['swap_with_location'])) {
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...
146
                //Swap locations
147
                $swapLocationId = $this->dsl['swap_with_location'];
148
                if ($this->referenceResolver->isReference($swapLocationId)) {
149
                    $swapLocationId = $this->referenceResolver->getReferenceValue($swapLocationId);
150
                }
151
                $locationToSwap = $locationService->loadLocation($swapLocationId);
152
153
                $locationService->swapLocation($location, $locationToSwap);
154
            }
155
156
            $this->setReferences($location);
157
        }
158
    }
159
160
    /**
161
     * Delete locations identified by their ids.
162
     *
163
     * @todo add support for flexible matchers
164
     */
165
    protected function delete()
166
    {
167
        $locationService = $this->repository->getLocationService();
168
169
        $locationCollection = $this->matchLocations('delete');
170
171
        foreach ($locationCollection as $location) {
0 ignored issues
show
Bug introduced by
The expression $locationCollection of type object<Kaliop\eZMigratio...ocationCollection>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
172
            //$location = $locationService->loadLocation($locationId);
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
173
            $locationService->deleteLocation($location);
174
        }
175
    }
176
177
    /**
178
     * @param string $action
179
     * @return ContentCollection
180
     * @throws \Exception
181
     */
182
    protected function matchLocations($action)
183
    {
184
        if (!isset($this->dsl['location_id'])&& !isset($this->dsl['match'])) {
185
            throw new \Exception("The ID or a Match Condition is required to $action a location.");
186
        }
187
188
        // Backwards compat
189
        if (!isset($this->dsl['match'])) {
190
            $this->dsl['match'] = array('location_id' => $this->dsl['location_id']);
191
        }
192
193
        $match = $this->dsl['match'];
194
195
        // convert the references passed in the match
196
        foreach ($match as $condition => $values) {
197
            if (is_array($values)) {
198
                foreach ($values as $position => $value) {
199
                    if ($this->referenceResolver->isReference($value)) {
200
                        $match[$condition][$position] = $this->referenceResolver->getReferenceValue($value);
201
                    }
202
                }
203
            } else {
204
                if ($this->referenceResolver->isReference($values)) {
205
                    $match[$condition] = $this->referenceResolver->getReferenceValue($values);
206
                }
207
            }
208
        }
209
210
        return $this->locationMatcher->match($match);
211
    }
212
213
    /**
214
     * NB: weirdly enough, it returns contents, not locations
215
     *
216
     * @param string $action
217
     * @return ContentCollection
218
     * @throws \Exception
219
     */
220 View Code Duplication
    protected function matchContents($action)
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...
221
    {
222
        if (!isset($this->dsl['object_id']) && !isset($this->dsl['remote_id']) && !isset($this->dsl['match'])) {
223
            throw new \Exception("The ID or remote ID of an object or a Match Condition is required to $action a new location.");
224
        }
225
226
        // Backwards compat
227
        if (!isset($this->dsl['match'])) {
228
            if (isset($this->dsl['object_id'])) {
229
                $this->dsl['match'] = array('content_id' => $this->dsl['object_id']);
230
            } elseif (isset($this->dsl['remote_id'])) {
231
                $this->dsl['match'] = array('content_remote_id' => $this->dsl['remote_id']);
232
            }
233
        }
234
235
        $match = $this->dsl['match'];
236
237
        // convert the references passed in the match
238
        foreach ($match as $condition => $values) {
239
            if (is_array($values)) {
240
                foreach ($values as $position => $value) {
241
                    if ($this->referenceResolver->isReference($value)) {
242
                        $match[$condition][$position] = $this->referenceResolver->getReferenceValue($value);
243
                    }
244
                }
245
            } else {
246
                if ($this->referenceResolver->isReference($values)) {
247
                    $match[$condition] = $this->referenceResolver->getReferenceValue($values);
248
                }
249
            }
250
        }
251
252
        return $this->contentMatcher->matchContent($match);
253
    }
254
255
    protected function getSortField($currentValue = null)
256
    {
257
        $sortField = Location::SORT_FIELD_PUBLISHED;
258
259
        if (!is_null($currentValue)) {
260
            $sortField = $currentValue;
261
        }
262
263
        if (isset($this->dsl['sort_field'])) {
264
            $sortFieldId = "SORT_FIELD_" . strtoupper($this->dsl['sort_field']);
265
266
            $ref = new \ReflectionClass('eZ\Publish\API\Repository\Values\Content\Location');
267
268
            $sortField = $ref->getConstant($sortFieldId);
269
        }
270
271
        return $sortField;
272
    }
273
274
    /**
275
     * Get the sort order based on the current value and the value in the DSL definition.
276
     *
277
     * If no current value is set and there is no value in the DSL it will default to Location::SORT_ORDER_ASC
278
     *
279
     * @see \eZ\Publish\API\Repository\Values\Content\Location::SORT_ORDER_*
280
     *
281
     * @param int $currentValue
282
     * @return int
283
     */
284
    protected function getSortOrder($currentValue = null)
285
    {
286
        $sortOrder = Location::SORT_ORDER_ASC;
287
        if (!is_null($currentValue)) {
288
            $sortOrder = $currentValue;
289
        }
290
291
        if (isset($this->dsl['sort_order'])) {
292
            if (strtoupper($this->dsl['sort_order']) === 'ASC') {
293
                $sortOrder = Location::SORT_ORDER_ASC;
294
            } else {
295
                $sortOrder = Location::SORT_ORDER_DESC;
296
            }
297
        }
298
299
        return $sortOrder;
300
    }
301
302
    /**
303
     * Sets references to object attributes
304
     *
305
     * The Location Manager currently supports setting references to location id.
306
     *
307
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute.
308
     * @param \eZ\Publish\API\Repository\Values\Content\Location|LocationCollection $location
309
     * @return boolean
310
     */
311
    protected function setReferences($location)
312
    {
313
        if (!array_key_exists('references', $this->dsl)) {
314
            return false;
315
        }
316
317
        if ($location instanceof LocationCollection) {
318
            if (count($location) > 1) {
319
                throw new \InvalidArgumentException('Location Manager does not support setting references for creating/updating of multiple locations');
320
            }
321
            $location = reset($location);
322
        }
323
324
        foreach ($this->dsl['references'] as $reference) {
325
            switch ($reference['attribute']) {
326
                case 'location_id':
327
                case 'id':
328
                    $value = $location->id;
329
                    break;
330
                case 'remote_id':
331
                case 'location_remote_id':
332
                    $value = $location->remoteId;
333
                    break;
334
                default:
335
                    throw new \InvalidArgumentException('Location Manager does not support setting references for attribute ' . $reference['attribute']);
336
            }
337
338
            $this->referenceResolver->addReference($reference['identifier'], $value);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Kaliop\eZMigrationBundle...erenceResolverInterface as the method addReference() does only exist in the following implementations of said interface: Kaliop\eZMigrationBundle...CustomReferenceResolver.

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...
339
        }
340
341
        return true;
342
    }
343
}
344