Completed
Pull Request — master (#62)
by
unknown
07:56
created

LocationManager   C

Complexity

Total Complexity 59

Size/Duplication

Total Lines 289
Duplicated Lines 15.22 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 13
Bugs 3 Features 5
Metric Value
c 13
b 3
f 5
dl 44
loc 289
rs 6.1904
wmc 59
lcom 1
cbo 9

8 Methods

Rating   Name   Duplication   Size   Complexity  
A getSortField() 0 18 3
A getSortOrder() 0 17 4
A __construct() 0 4 1
D create() 0 40 9
F update() 10 76 19
A delete() 0 17 4
C matchContents() 34 34 12
C setReferences() 0 28 7

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like LocationManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use LocationManager, and based on these observations, apply Extract Interface, too.

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
10
class LocationManager extends RepositoryExecutor
11
{
12
    protected $supportedStepTypes = array('location');
13
14
    protected $contentMatcher;
15
16
    public function __construct(ContentMatcher $contentMatcher)
17
    {
18
        $this->contentMatcher = $contentMatcher;
19
    }
20
21
    /**
22
     * Method to handle the create operation of the migration instructions
23
     */
24
    protected function create()
25
    {
26
        $locationService = $this->repository->getLocationService();
27
28
        if (!isset($this->dsl['parent_location_id'])) {
29
            throw new \Exception('Missing parent location id. This is required to create the new location.');
30
        }
31
        if (!is_array($this->dsl['parent_location_id'])) {
32
            $this->dsl['parent_location_id'] = array($this->dsl['parent_location_id']);
33
        }
34
        foreach ($this->dsl['parent_location_id'] as $id => $parentLocationId) {
35
            if ($this->referenceResolver->isReference($parentLocationId)) {
36
                $this->dsl['parent_location_id'][$id] = $this->referenceResolver->getReferenceValue($parentLocationId);
37
            }
38
        }
39
40
        $contentCollection = $this->matchContents('create');
41
42
        $locations = null;
43
        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...
44
            $contentInfo = $content->contentInfo;
45
46
            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...
47
                $locationCreateStruct = $locationService->newLocationCreateStruct($parentLocationId);
48
49
                $locationCreateStruct->hidden = isset($this->dsl['is_hidden']) ?: false;
50
51
                if (isset($this->dsl['priority'])) {
52
                    $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...
53
                }
54
55
                $locationCreateStruct->sortOrder = $this->getSortOrder();
56
                $locationCreateStruct->sortField = $this->getSortField();
57
58
                $locations[] = $locationService->createLocation($contentInfo, $locationCreateStruct);
59
            }
60
        }
61
62
        $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...
63
    }
64
65
    /**
66
     * Updates basic information for a location like priority, sort field and sort order.
67
     * Updates the visibility of the location when needed.
68
     * Can move a location and its children to a new parent location or swap two locations.
69
     *
70
     * @todo add support for flexible matchers
71
     */
72
    protected function update()
73
    {
74
        $locationService = $this->repository->getLocationService();
75
76
        if (!isset($this->dsl['location_id'])) {
77
            throw new \Exception('No location set for update.');
78
        }
79
80
        if (isset($this->dsl['swap_with_location']) && isset($this->dsl['patent_location_id'])) {
81
            throw new \Exception('Cannot move location to a new parent and swap location with another location at the same time.');
82
        }
83
84
        $locationId = $this->dsl['location_id'];
85
        if ($this->referenceResolver->isReference($locationId)) {
86
            $locationId = $this->referenceResolver->getReferenceValue($locationId);
87
        }
88
89
        $location = $locationService->loadLocation($locationId);
90
91
        if (array_key_exists('priority', $this->dsl)
92
            || array_key_exists('sort_field', $this->dsl)
93
            || array_key_exists('sort_order', $this->dsl)
94
            || array_key_exists('remote_id', $this->dsl)
95
        ) {
96
            $locationUpdateStruct = $locationService->newLocationUpdateStruct();
97
98
            if (isset($this->dsl['priority'])) {
99
                $locationUpdateStruct->priority = $this->dsl['priority'];
100
            }
101
102
            if (isset($this->dsl['sort_field'])) {
103
                $locationUpdateStruct->sortField = $this->getSortField($location->sortField);
104
            }
105
106
            if (isset($this->dsl['sort_order'])) {
107
                $locationUpdateStruct->sortOrder = $this->getSortOrder($location->sortOrder);
108
            }
109
110
            if (isset($this->dsl['remote_id'])) {
111
                $locationUpdateStruct->remoteId = $this->dsl['remote_id'];
112
            }
113
114
            $locationService->updateLocation($location, $locationUpdateStruct);
115
        }
116
117
        // Check if visibility needs to be updated
118
        if (isset($this->dsl['is_hidden'])) {
119
            if ($this->dsl['is_hidden']) {
120
                $locationService->hideLocation($location);
121
            } else {
122
                $locationService->unhideLocation($location);
123
            }
124
        }
125
126
        // Move or swap location
127
        if (isset($this->dsl['parent_location_id'])) {
128
            // Move the location and all it's children to a new parent
129
            $parentLocationId = $this->dsl['parent_location_id'];
130
            if ($this->referenceResolver->isReference($parentLocationId)) {
131
                $parentLocationId = $this->referenceResolver->getReferenceValue($parentLocationId);
132
            }
133
            $newParentLocation = $locationService->loadLocation($parentLocationId);
134
            $locationService->moveSubtree($location, $newParentLocation);
135 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...
136
            //Swap locations
137
            $swapLocationId = $this->dsl['swap_with_location'];
138
            if ($this->referenceResolver->isReference($swapLocationId)) {
139
                $swapLocationId = $this->referenceResolver->getReferenceValue($swapLocationId);
140
            }
141
            $locationToSwap = $locationService->loadLocation($swapLocationId);
142
143
            $locationService->swapLocation($location, $locationToSwap);
144
        }
145
146
        $this->setReferences($location);
147
    }
148
149
    /**
150
     * Delete locations identified by their ids.
151
     *
152
     * @todo add support for flexible matchers
153
     */
154
    protected function delete()
155
    {
156
        $locationService = $this->repository->getLocationService();
157
158
        if (!isset($this->dsl['location_id'])) {
159
            throw new \Exception('No location provided for deletion');
160
        }
161
162
        if (!is_array($this->dsl['location_id'])) {
163
            $this->dsl['location_id'] = array($this->dsl['location_id']);
164
        }
165
166
        foreach ($this->dsl['location_id'] as $locationId) {
167
            $location = $locationService->loadLocation($locationId);
168
            $locationService->deleteLocation($location);
169
        }
170
    }
171
172
    /**
173
     * NB: weirdly enough, it returns contents, not locations
174
     *
175
     * @param string $action
176
     * @return ContentCollection
177
     * @throws \Exception
178
     */
179 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...
180
    {
181
        if (!isset($this->dsl['object_id']) && !isset($this->dsl['remote_id']) && !isset($this->dsl['match'])) {
182
            throw new \Exception("The ID or remote ID of an object or a Match Condition is required to $action a new location.");
183
        }
184
185
        // Backwards compat
186
        if (!isset($this->dsl['match'])) {
187
            if (isset($this->dsl['object_id'])) {
188
                $this->dsl['match'] = array('content_id' => $this->dsl['object_id']);
189
            } elseif (isset($this->dsl['remote_id'])) {
190
                $this->dsl['match'] = array('content_remote_id' => $this->dsl['remote_id']);
191
            }
192
        }
193
194
        $match = $this->dsl['match'];
195
196
        // convert the references passed in the match
197
        foreach ($match as $condition => $values) {
198
            if (is_array($values)) {
199
                foreach ($values as $position => $value) {
200
                    if ($this->referenceResolver->isReference($value)) {
201
                        $match[$condition][$position] = $this->referenceResolver->getReferenceValue($value);
202
                    }
203
                }
204
            } else {
205
                if ($this->referenceResolver->isReference($values)) {
206
                    $match[$condition] = $this->referenceResolver->getReferenceValue($values);
207
                }
208
            }
209
        }
210
211
        return $this->contentMatcher->matchContent($match);
212
    }
213
214
    protected function getSortField($currentValue = null)
215
    {
216
        $sortField = Location::SORT_FIELD_PUBLISHED;
217
218
        if (!is_null($currentValue)) {
219
            $sortField = $currentValue;
220
        }
221
222
        if (isset($this->dsl['sort_field'])) {
223
            $sortFieldId = "SORT_FIELD_" . strtoupper($this->dsl['sort_field']);
224
225
            $ref = new \ReflectionClass('eZ\Publish\API\Repository\Values\Content\Location');
226
227
            $sortField = $ref->getConstant($sortFieldId);
228
        }
229
230
        return $sortField;
231
    }
232
233
    /**
234
     * Get the sort order based on the current value and the value in the DSL definition.
235
     *
236
     * If no current value is set and there is no value in the DSL it will default to Location::SORT_ORDER_ASC
237
     *
238
     * @see \eZ\Publish\API\Repository\Values\Content\Location::SORT_ORDER_*
239
     *
240
     * @param int $currentValue
241
     * @return int
242
     */
243
    protected function getSortOrder($currentValue = null)
244
    {
245
        $sortOrder = Location::SORT_ORDER_ASC;
246
        if (!is_null($currentValue)) {
247
            $sortOrder = $currentValue;
248
        }
249
250
        if (isset($this->dsl['sort_order'])) {
251
            if (strtoupper($this->dsl['sort_order']) === 'ASC') {
252
                $sortOrder = Location::SORT_ORDER_ASC;
253
            } else {
254
                $sortOrder = Location::SORT_ORDER_DESC;
255
            }
256
        }
257
258
        return $sortOrder;
259
    }
260
261
    /**
262
     * Sets references to object attributes
263
     *
264
     * The Location Manager currently supports setting references to location id.
265
     *
266
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute.
267
     * @param \eZ\Publish\API\Repository\Values\Content\Location|LocationCollection $location
268
     * @return boolean
269
     */
270
    protected function setReferences($location)
271
    {
272
        if (!array_key_exists('references', $this->dsl)) {
273
            return false;
274
        }
275
276
        if ($location instanceof LocationCollection) {
277
            if (count($location) > 1) {
278
                throw new \InvalidArgumentException('Location Manager does not support setting references for creating/updating of multiple locations');
279
            }
280
            $location = reset($location);
281
        }
282
283
        foreach ($this->dsl['references'] as $reference) {
284
            switch ($reference['attribute']) {
285
                case 'location_id':
286
                case 'id':
287
                    $value = $location->id;
288
                    break;
289
                default:
290
                    throw new \InvalidArgumentException('Location Manager does not support setting references for attribute ' . $reference['attribute']);
291
            }
292
293
            $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...
294
        }
295
296
        return true;
297
    }
298
}
299