Completed
Push — master ( caf771...f662c4 )
by Gaetano
07:54
created

LocationManager::matchLocations()   D

Complexity

Conditions 9
Paths 11

Size

Total Lines 30
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 15
c 1
b 0
f 0
nc 11
nop 1
dl 0
loc 30
rs 4.909
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
            ) {
105
                $locationUpdateStruct = $locationService->newLocationUpdateStruct();
106
107
                if (isset($this->dsl['priority'])) {
108
                    $locationUpdateStruct->priority = $this->dsl['priority'];
109
                }
110
111
                if (isset($this->dsl['sort_field'])) {
112
                    $locationUpdateStruct->sortField = $this->getSortField($location->sortField);
113
                }
114
115
                if (isset($this->dsl['sort_order'])) {
116
                    $locationUpdateStruct->sortOrder = $this->getSortOrder($location->sortOrder);
117
                }
118
119
                $locationService->updateLocation($location, $locationUpdateStruct);
120
            }
121
122
            // Check if visibility needs to be updated
123
            if (isset($this->dsl['is_hidden'])) {
124
                if ($this->dsl['is_hidden']) {
125
                    $locationService->hideLocation($location);
126
                } else {
127
                    $locationService->unhideLocation($location);
128
                }
129
            }
130
131
            // Move or swap location
132
            if (isset($this->dsl['parent_location_id'])) {
133
                // Move the location and all it's children to a new parent
134
                $parentLocationId = $this->dsl['parent_location_id'];
135
                if ($this->referenceResolver->isReference($parentLocationId)) {
136
                    $parentLocationId = $this->referenceResolver->getReferenceValue($parentLocationId);
137
                }
138
                $newParentLocation = $locationService->loadLocation($parentLocationId);
139
                $locationService->moveSubtree($location, $newParentLocation);
140 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...
141
                //Swap locations
142
                $swapLocationId = $this->dsl['swap_with_location'];
143
                if ($this->referenceResolver->isReference($swapLocationId)) {
144
                    $swapLocationId = $this->referenceResolver->getReferenceValue($swapLocationId);
145
                }
146
                $locationToSwap = $locationService->loadLocation($swapLocationId);
147
148
                $locationService->swapLocation($location, $locationToSwap);
149
            }
150
151
            $this->setReferences($location);
152
        }
153
    }
154
155
    /**
156
     * Delete locations identified by their ids.
157
     *
158
     * @todo add support for flexible matchers
159
     */
160
    protected function delete()
161
    {
162
        $locationService = $this->repository->getLocationService();
163
164
        $locationCollection = $this->matchLocations('delete');
165
166
        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...
167
            //$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...
168
            $locationService->deleteLocation($location);
169
        }
170
    }
171
172
    /**
173
     * @param string $action
174
     * @return ContentCollection
175
     * @throws \Exception
176
     */
177
    protected function matchLocations($action)
178
    {
179
        if (!isset($this->dsl['location_id'])&& !isset($this->dsl['match'])) {
180
            throw new \Exception("The ID or a Match Condition is required to $action a location.");
181
        }
182
183
        // Backwards compat
184
        if (!isset($this->dsl['match'])) {
185
            $this->dsl['match'] = array('location_id' => $this->dsl['location_id']);
186
        }
187
188
        $match = $this->dsl['match'];
189
190
        // convert the references passed in the match
191
        foreach ($match as $condition => $values) {
192
            if (is_array($values)) {
193
                foreach ($values as $position => $value) {
194
                    if ($this->referenceResolver->isReference($value)) {
195
                        $match[$condition][$position] = $this->referenceResolver->getReferenceValue($value);
196
                    }
197
                }
198
            } else {
199
                if ($this->referenceResolver->isReference($values)) {
200
                    $match[$condition] = $this->referenceResolver->getReferenceValue($values);
201
                }
202
            }
203
        }
204
205
        return $this->locationMatcher->match($match);
206
    }
207
208
    /**
209
     * NB: weirdly enough, it returns contents, not locations
210
     *
211
     * @param string $action
212
     * @return ContentCollection
213
     * @throws \Exception
214
     */
215 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...
216
    {
217
        if (!isset($this->dsl['object_id']) && !isset($this->dsl['remote_id']) && !isset($this->dsl['match'])) {
218
            throw new \Exception("The ID or remote ID of an object or a Match Condition is required to $action a new location.");
219
        }
220
221
        // Backwards compat
222
        if (!isset($this->dsl['match'])) {
223
            if (isset($this->dsl['object_id'])) {
224
                $this->dsl['match'] = array('content_id' => $this->dsl['object_id']);
225
            } elseif (isset($this->dsl['remote_id'])) {
226
                $this->dsl['match'] = array('content_remote_id' => $this->dsl['remote_id']);
227
            }
228
        }
229
230
        $match = $this->dsl['match'];
231
232
        // convert the references passed in the match
233
        foreach ($match as $condition => $values) {
234
            if (is_array($values)) {
235
                foreach ($values as $position => $value) {
236
                    if ($this->referenceResolver->isReference($value)) {
237
                        $match[$condition][$position] = $this->referenceResolver->getReferenceValue($value);
238
                    }
239
                }
240
            } else {
241
                if ($this->referenceResolver->isReference($values)) {
242
                    $match[$condition] = $this->referenceResolver->getReferenceValue($values);
243
                }
244
            }
245
        }
246
247
        return $this->contentMatcher->matchContent($match);
248
    }
249
250
    protected function getSortField($currentValue = null)
251
    {
252
        $sortField = Location::SORT_FIELD_PUBLISHED;
253
254
        if (!is_null($currentValue)) {
255
            $sortField = $currentValue;
256
        }
257
258
        if (isset($this->dsl['sort_field'])) {
259
            $sortFieldId = "SORT_FIELD_" . strtoupper($this->dsl['sort_field']);
260
261
            $ref = new \ReflectionClass('eZ\Publish\API\Repository\Values\Content\Location');
262
263
            $sortField = $ref->getConstant($sortFieldId);
264
        }
265
266
        return $sortField;
267
    }
268
269
    /**
270
     * Get the sort order based on the current value and the value in the DSL definition.
271
     *
272
     * If no current value is set and there is no value in the DSL it will default to Location::SORT_ORDER_ASC
273
     *
274
     * @see \eZ\Publish\API\Repository\Values\Content\Location::SORT_ORDER_*
275
     *
276
     * @param int $currentValue
277
     * @return int
278
     */
279
    protected function getSortOrder($currentValue = null)
280
    {
281
        $sortOrder = Location::SORT_ORDER_ASC;
282
        if (!is_null($currentValue)) {
283
            $sortOrder = $currentValue;
284
        }
285
286
        if (isset($this->dsl['sort_order'])) {
287
            if (strtoupper($this->dsl['sort_order']) === 'ASC') {
288
                $sortOrder = Location::SORT_ORDER_ASC;
289
            } else {
290
                $sortOrder = Location::SORT_ORDER_DESC;
291
            }
292
        }
293
294
        return $sortOrder;
295
    }
296
297
    /**
298
     * Sets references to object attributes
299
     *
300
     * The Location Manager currently supports setting references to location id.
301
     *
302
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute.
303
     * @param \eZ\Publish\API\Repository\Values\Content\Location|LocationCollection $location
304
     * @return boolean
305
     */
306
    protected function setReferences($location)
307
    {
308
        if (!array_key_exists('references', $this->dsl)) {
309
            return false;
310
        }
311
312
        if ($location instanceof LocationCollection) {
313
            if (count($location) > 1) {
314
                throw new \InvalidArgumentException('Location Manager does not support setting references for creating/updating of multiple locations');
315
            }
316
            $location = reset($location);
317
        }
318
319
        foreach ($this->dsl['references'] as $reference) {
320
            switch ($reference['attribute']) {
321
                case 'location_id':
322
                case 'id':
323
                    $value = $location->id;
324
                    break;
325
                case 'remote_id':
326
                case 'location_remote_id':
327
                    $value = $location->remoteId;
328
                    break;
329
                default:
330
                    throw new \InvalidArgumentException('Location Manager does not support setting references for attribute ' . $reference['attribute']);
331
            }
332
333
            $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...
334
        }
335
336
        return true;
337
    }
338
}
339