Completed
Push — master ( 492c7b...fba654 )
by Gaetano
53:32 queued 50:57
created

ContentManager   F

Complexity

Total Complexity 122

Size/Duplication

Total Lines 719
Duplicated Lines 9.46 %

Coupling/Cohesion

Components 1
Dependencies 28

Test Coverage

Coverage 92.03%

Importance

Changes 0
Metric Value
wmc 122
lcom 1
cbo 28
dl 68
loc 719
ccs 335
cts 364
cp 0.9203
rs 1.0434
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 19 1
F create() 9 133 25
A load() 0 8 1
F update() 4 92 24
A delete() 0 19 3
C matchContents() 23 23 7
D setReferences() 3 118 31
D generateMigration() 21 101 10
B setFields() 0 30 6
A setSection() 8 8 1
A setObjectStates() 0 11 2
A setMainLocation() 0 18 4
A getFieldValue() 0 12 3
A getSingleFieldValue() 0 10 1
A getUser() 0 5 1
A toDateTime() 0 8 2

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 ContentManager 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 ContentManager, 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\ContentType\ContentType;
6
use eZ\Publish\API\Repository\Values\ContentType\FieldDefinition;
7
use eZ\Publish\API\Repository\Values\Content\Location;
8
use eZ\Publish\API\Repository\Values\Content\Content;
9
use eZ\Publish\API\Repository\Values\Content\ContentCreateStruct;
10
use eZ\Publish\API\Repository\Values\Content\ContentUpdateStruct;
11
use eZ\Publish\Core\Base\Exceptions\NotFoundException;
12
use Kaliop\eZMigrationBundle\API\Collection\ContentCollection;
13
use Kaliop\eZMigrationBundle\API\MigrationGeneratorInterface;
14
use Kaliop\eZMigrationBundle\Core\FieldHandlerManager;
15
use Kaliop\eZMigrationBundle\Core\Matcher\ContentMatcher;
16
use Kaliop\eZMigrationBundle\Core\Matcher\SectionMatcher;
17
use Kaliop\eZMigrationBundle\Core\Matcher\UserMatcher;
18
use Kaliop\eZMigrationBundle\Core\Matcher\ObjectStateMatcher;
19
use Kaliop\eZMigrationBundle\Core\Matcher\ObjectStateGroupMatcher;
20
use Kaliop\eZMigrationBundle\Core\Helper\SortConverter;
21
use JmesPath\Env as JmesPath;
22
23
/**
24
 * Handles content migrations.
25
 *
26
 * @todo add support for updating of content metadata
27
 */
28
class ContentManager extends RepositoryExecutor implements MigrationGeneratorInterface
29
{
30
    protected $supportedStepTypes = array('content');
31
    protected $supportedActions = array('create', 'load', 'update', 'delete');
32
33
    protected $contentMatcher;
34
    protected $sectionMatcher;
35
    protected $userMatcher;
36
    protected $objectStateMatcher;
37
    protected $objectStateGroupMatcher;
38
    protected $fieldHandlerManager;
39
    protected $locationManager;
40
    protected $sortConverter;
41
42 72
    public function __construct(
43
        ContentMatcher $contentMatcher,
44
        SectionMatcher $sectionMatcher,
45
        UserMatcher $userMatcher,
46
        ObjectStateMatcher $objectStateMatcher,
47
        ObjectStateGroupMatcher $objectStateGroupMatcher,
48
        FieldHandlerManager $fieldHandlerManager,
49
        LocationManager $locationManager,
50
        SortConverter $sortConverter
51
    ) {
52 72
        $this->contentMatcher = $contentMatcher;
53 72
        $this->sectionMatcher = $sectionMatcher;
54 72
        $this->userMatcher = $userMatcher;
55 72
        $this->objectStateMatcher = $objectStateMatcher;
56 72
        $this->objectStateGroupMatcher = $objectStateGroupMatcher;
57 72
        $this->fieldHandlerManager = $fieldHandlerManager;
58 72
        $this->locationManager = $locationManager;
59 72
        $this->sortConverter = $sortConverter;
60 72
    }
61
62
    /**
63
     * Handles the content create migration action type
64
     */
65 11
    protected function create($step)
66
    {
67 11
        $contentService = $this->repository->getContentService();
68 11
        $locationService = $this->repository->getLocationService();
69 11
        $contentTypeService = $this->repository->getContentTypeService();
70
71 11
        $contentTypeIdentifier = $step->dsl['content_type'];
72 11
        $contentTypeIdentifier = $this->referenceResolver->resolveReference($contentTypeIdentifier);
73
        /// @todo use a contenttypematcher
74 11
        $contentType = $contentTypeService->loadContentTypeByIdentifier($contentTypeIdentifier);
75
76 11
        $contentCreateStruct = $contentService->newContentCreateStruct($contentType, $this->getLanguageCode($step));
77
78 11
        $this->setFields($contentCreateStruct, $step->dsl['attributes'], $contentType, $step);
79
80 11
        if (isset($step->dsl['always_available'])) {
81
            $contentCreateStruct->alwaysAvailable = $step->dsl['always_available'];
82
        } else {
83
            // Could be removed when https://github.com/ezsystems/ezpublish-kernel/pull/1874 is merged,
84
            // but we strive to support old eZ kernel versions as well...
85 11
            $contentCreateStruct->alwaysAvailable = $contentType->defaultAlwaysAvailable;
86
        }
87
88 11
        if (isset($step->dsl['remote_id'])) {
89 3
            $contentCreateStruct->remoteId = $step->dsl['remote_id'];
90
        }
91
92 11 View Code Duplication
        if (isset($step->dsl['section'])) {
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...
93 1
            $sectionKey = $this->referenceResolver->resolveReference($step->dsl['section']);
94 1
            $section = $this->sectionMatcher->matchOneByKey($sectionKey);
95 1
            $contentCreateStruct->sectionId = $section->id;
96
        }
97
98 11 View Code Duplication
        if (isset($step->dsl['owner'])) {
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...
99 2
            $owner = $this->getUser($step->dsl['owner']);
100 2
            $contentCreateStruct->ownerId = $owner->id;
101
        }
102
103
        // This is a bit tricky, as the eZPublish API does not support having a different creator and owner with only 1 version.
104
        // We allow it, hoping that nothing gets broken because of it
105 11
        if (isset($step->dsl['version_creator'])) {
106 1
            $realContentOwnerId = $contentCreateStruct->ownerId;
107 1
            if ($realContentOwnerId == null) {
108 1
                $realContentOwnerId = $this->repository->getCurrentUser()->id;
109
            }
110 1
            $versionCreator = $this->getUser($step->dsl['version_creator']);
111 1
            $contentCreateStruct->ownerId = $versionCreator->id;
112
        }
113
114 11
        if (isset($step->dsl['modification_date'])) {
115 1
            $contentCreateStruct->modificationDate = $this->toDateTime($step->dsl['modification_date']);
116
        }
117
118
        // instantiate a location create struct from the parent location:
119
        // BC
120 11
        $locationId = isset($step->dsl['parent_location']) ? $step->dsl['parent_location'] : (
121 11
            isset($step->dsl['main_location']) ? $step->dsl['main_location'] : null
122
        );
123
        // 1st resolve references
124 11
        $locationId = $this->referenceResolver->resolveReference($locationId);
125
        // 2nd allow to specify the location via remote_id
126 11
        $locationId = $this->locationManager->matchLocationByKey($locationId)->id;
127 11
        $locationCreateStruct = $locationService->newLocationCreateStruct($locationId);
128
129 11
        if (isset($step->dsl['location_remote_id'])) {
130 2
            $locationCreateStruct->remoteId = $step->dsl['location_remote_id'];
131
        }
132
133 11
        if (isset($step->dsl['priority'])) {
134 1
            $locationCreateStruct->priority = $step->dsl['priority'];
135
        }
136
137 11
        if (isset($step->dsl['is_hidden'])) {
138 1
            $locationCreateStruct->hidden = $step->dsl['is_hidden'];
139
        }
140
141 11
        if (isset($step->dsl['sort_field'])) {
142 1
            $locationCreateStruct->sortField = $this->sortConverter->hash2SortField($step->dsl['sort_field']);
143
        } else {
144 11
            $locationCreateStruct->sortField = $contentType->defaultSortField;
145
        }
146
147 11
        if (isset($step->dsl['sort_order'])) {
148 1
            $locationCreateStruct->sortOrder = $this->sortConverter->hash2SortOrder($step->dsl['sort_order']);
149
        } else {
150 11
            $locationCreateStruct->sortOrder = $contentType->defaultSortOrder;
151
        }
152
153 11
        $locations = array($locationCreateStruct);
154
155
        // BC
156 11
        $other_locations = isset($step->dsl['other_parent_locations']) ? $step->dsl['other_parent_locations'] : (
157 11
            isset($step->dsl['other_locations']) ? $step->dsl['other_locations'] : null
158
        );
159 11
        if (isset($other_locations)) {
160
            foreach ($other_locations as $locationId) {
161
                $locationId = $this->referenceResolver->resolveReference($locationId);
162
                $locationId = $this->locationManager->matchLocationByKey($locationId)->id;
163
                $secondaryLocationCreateStruct = $locationService->newLocationCreateStruct($locationId);
164
                array_push($locations, $secondaryLocationCreateStruct);
165
            }
166
        }
167
168
        // create a draft using the content and location create struct and publish it
169 11
        $draft = $contentService->createContent($contentCreateStruct, $locations);
170 10
        $content = $contentService->publishVersion($draft->versionInfo);
171
172 10
        if (isset($step->dsl['object_states'])) {
173 2
            $this->setObjectStates($content, $step->dsl['object_states']);
174
        }
175
176
        // 2nd part of the hack: re-set the content owner to its intended value
177 10
        if (isset($step->dsl['version_creator']) || isset($step->dsl['publication_date'])) {
178 1
            $contentMetaDataUpdateStruct = $contentService->newContentMetadataUpdateStruct();
179
180 1
            if (isset($step->dsl['version_creator'])) {
181 1
                $contentMetaDataUpdateStruct->ownerId = $realContentOwnerId;
0 ignored issues
show
Bug introduced by
The variable $realContentOwnerId does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
182
            }
183 1
            if (isset($step->dsl['publication_date'])) {
184 1
                $contentMetaDataUpdateStruct->publishedDate = $this->toDateTime($step->dsl['publication_date']);
185
            }
186
            // we have to do this to make sure we preserve the custom modification date
187 1
            if (isset($this->dsl['modification_date'])) {
188
                $contentMetaDataUpdateStruct->modificationDate = $this->toDateTime($this->dsl['modification_date']);
0 ignored issues
show
Bug introduced by
The property dsl does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
189
            }
190
191 1
            $contentService->updateContentMetadata($content->contentInfo, $contentMetaDataUpdateStruct);
192
        }
193
194 10
        $this->setReferences($content, $step);
195
196 10
        return $content;
197
    }
198
199 4
    protected function load($step)
200
    {
201 4
        $contentCollection = $this->matchContents('load', $step);
202
203 4
        $this->setReferences($contentCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $contentCollection defined by $this->matchContents('load', $step) on line 201 can be null; however, Kaliop\eZMigrationBundle...anager::setReferences() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
204
205 4
        return $contentCollection;
206
    }
207
208
    /**
209
     * Handles the content update migration action type
210
     *
211
     * @todo handle updating of more metadata fields
212
     */
213 9
    protected function update($step)
214
    {
215 9
        $contentService = $this->repository->getContentService();
216 9
        $contentTypeService = $this->repository->getContentTypeService();
217
218 9
        $contentCollection = $this->matchContents('update', $step);
219
220 9
        if (count($contentCollection) > 1 && isset($step->dsl['references'])) {
221
            throw new \Exception("Can not execute Content update because multiple contents match, and a references section is specified in the dsl. References can be set when only 1 content matches");
222
        }
223
224 9
        if (count($contentCollection) > 1 && isset($step->dsl['main_location'])) {
225
            throw new \Exception("Can not execute Content update because multiple contents match, and a main_location section is specified in the dsl. References can be set when only 1 content matches");
226
        }
227
228 9
        $contentType = array();
229
230 9
        foreach ($contentCollection as $key => $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...
231 9
            $contentInfo = $content->contentInfo;
232
233 9
            if (!isset($contentType[$contentInfo->contentTypeId])) {
234 9
                $contentType[$contentInfo->contentTypeId] = $contentTypeService->loadContentType($contentInfo->contentTypeId);
235
            }
236
237 9
            if (isset($step->dsl['attributes']) || isset($step->dsl['version_creator'])) {
238 4
                $contentUpdateStruct = $contentService->newContentUpdateStruct();
239
240 4
                if (isset($step->dsl['attributes'])) {
241 4
                    $this->setFields($contentUpdateStruct, $step->dsl['attributes'], $contentType[$contentInfo->contentTypeId], $step);
242
                }
243
244 4
                $versionCreator = null;
245 4
                if (isset($step->dsl['version_creator'])) {
246 1
                    $versionCreator = $this->getUser($step->dsl['version_creator']);
247
                }
248
249 4
                $draft = $contentService->createContentDraft($contentInfo, null, $versionCreator);
250 4
                $contentService->updateContent($draft->versionInfo, $contentUpdateStruct);
251 4
                $content = $contentService->publishVersion($draft->versionInfo);
252
            }
253
254 9
            if (isset($step->dsl['always_available']) ||
255 9
                isset($step->dsl['new_remote_id']) ||
256 8
                isset($step->dsl['owner']) ||
257 7
                isset($step->dsl['modification_date']) ||
258 9
                isset($step->dsl['publication_date'])) {
259
260 2
                $contentMetaDataUpdateStruct = $contentService->newContentMetadataUpdateStruct();
261
262 2
                if (isset($step->dsl['always_available'])) {
263
                    $contentMetaDataUpdateStruct->alwaysAvailable = $step->dsl['always_available'];
264
                }
265
266 2
                if (isset($step->dsl['new_remote_id'])) {
267 1
                    $contentMetaDataUpdateStruct->remoteId = $step->dsl['new_remote_id'];
268
                }
269
270 2 View Code Duplication
                if (isset($step->dsl['owner'])) {
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...
271 2
                    $owner = $this->getUser($step->dsl['owner']);
272 2
                    $contentMetaDataUpdateStruct->ownerId = $owner->id;
273
                }
274
275 2
                if (isset($step->dsl['modification_date'])) {
276 1
                    $contentMetaDataUpdateStruct->modificationDate = $this->toDateTime($step->dsl['modification_date']);
277
                }
278
279 2
                if (isset($step->dsl['publication_date'])) {
280 1
                    $contentMetaDataUpdateStruct->publishedDate = $this->toDateTime($step->dsl['publication_date']);
281
                }
282
283 2
                $content = $contentService->updateContentMetadata($content->contentInfo, $contentMetaDataUpdateStruct);
284
            }
285
286 9
            if (isset($step->dsl['section'])) {
287 1
                $this->setSection($content, $step->dsl['section']);
288
            }
289
290 9
            if (isset($step->dsl['object_states'])) {
291 1
                $this->setObjectStates($content, $step->dsl['object_states']);
292
            }
293
294 9
            if (isset($step->dsl['main_location'])) {
295 1
                $this->setMainLocation($content, $step->dsl['main_location']);
296
297
            }
298 9
            $contentCollection[$key] = $content;
299
        }
300
301 9
        $this->setReferences($contentCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $contentCollection defined by $this->matchContents('update', $step) on line 218 can be null; however, Kaliop\eZMigrationBundle...anager::setReferences() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
302
303 9
        return $contentCollection;
304
    }
305
306
    /**
307
     * Handles the content delete migration action type
308
     */
309 9
    protected function delete($step)
310
    {
311 9
        $contentCollection = $this->matchContents('delete', $step);
312
313 9
        $this->setReferences($contentCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $contentCollection defined by $this->matchContents('delete', $step) on line 311 can be null; however, Kaliop\eZMigrationBundle...anager::setReferences() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
314
315 9
        $contentService = $this->repository->getContentService();
316
317 9
        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...
318
            try {
319 9
                $contentService->deleteContent($content->contentInfo);
320 9
            } catch (NotFoundException $e) {
321
                // Someone else (or even us, by virtue of location tree?) removed the content which we found just a
322
                // second ago. We can safely ignore this
323
            }
324
        }
325
326 9
        return $contentCollection;
327
    }
328
329
    /**
330
     * @param string $action
331
     * @return ContentCollection
332
     * @throws \Exception
333
     */
334 11 View Code Duplication
    protected function matchContents($action, $step)
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...
335
    {
336 11
        if (!isset($step->dsl['object_id']) && !isset($step->dsl['remote_id']) && !isset($step->dsl['match'])) {
337
            throw new \Exception("The id or remote id of an object or a match condition is required to $action a content");
338
        }
339
340
        // Backwards compat
341
342 11
        if (isset($step->dsl['match'])) {
343 11
            $match = $step->dsl['match'];
344
        } else {
345 1
            if (isset($step->dsl['object_id'])) {
346 1
                $match = array('content_id' => $step->dsl['object_id']);
347
            } elseif (isset($step->dsl['remote_id'])) {
348
                $match = array('content_remote_id' => $step->dsl['remote_id']);
349
            }
350
        }
351
352
        // convert the references passed in the match
353 11
        $match = $this->resolveReferencesRecursively($match);
0 ignored issues
show
Bug introduced by
The variable $match does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Deprecated Code introduced by
The method Kaliop\eZMigrationBundle...ReferencesRecursively() has been deprecated with message: will be moved into the reference resolver classes

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
354
355 11
        return $this->contentMatcher->match($match);
356
    }
357
358
    /**
359
     * Sets references to certain content attributes.
360
     *
361
     * @param \eZ\Publish\API\Repository\Values\Content\Content|ContentCollection $content
362
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute
363
     * @return boolean
364
     *
365
     * @todo add support for other attributes... ?
366
     */
367 12
    protected function setReferences($content, $step)
368
    {
369 12
        if (!array_key_exists('references', $step->dsl)) {
370 12
            return false;
371
        }
372
373 8
        $references = $this->setReferencesCommon($content, $step->dsl['references']);
374 8
        $content = $this->insureSingleEntity($content, $references);
375
376 8
        foreach ($references as $reference) {
377
378 8
            switch ($reference['attribute']) {
379 8
                case 'object_id':
380 8
                case 'content_id':
381 8
                case 'id':
382 8
                    $value = $content->id;
383 8
                    break;
384 7
                case 'remote_id':
385 7
                case 'content_remote_id':
386 2
                    $value = $content->contentInfo->remoteId;
387 2
                    break;
388 7
                case 'always_available':
389 1
                    $value = $content->contentInfo->alwaysAvailable;
390 1
                    break;
391 7
                case 'content_type_id':
392 1
                    $value = $content->contentInfo->contentTypeId;
393 1
                    break;
394 7
                case 'content_type_identifier':
395 1
                    $contentTypeService = $this->repository->getContentTypeService();
396 1
                    $value = $contentTypeService->loadContentType($content->contentInfo->contentTypeId)->identifier;
397 1
                    break;
398 7
                case 'current_version':
399 7
                case 'current_version_no':
400 1
                    $value = $content->contentInfo->currentVersionNo;
401 1
                    break;
402 7
                case 'location_id':
403 5
                case 'main_location_id':
404 3
                    $value = $content->contentInfo->mainLocationId;
405 3
                    break;
406 5
                case 'main_language_code':
407 1
                    $value = $content->contentInfo->mainLanguageCode;
408 1
                    break;
409 5
                case 'modification_date':
410 1
                    $value = $content->contentInfo->modificationDate->getTimestamp();
411 1
                    break;
412 5
                case 'name':
413 1
                    $value = $content->contentInfo->name;
414 1
                    break;
415 5
                case 'owner_id':
416 1
                    $value = $content->contentInfo->ownerId;
417 1
                    break;
418 5
                case 'path':
419 2
                    $locationService = $this->repository->getLocationService();
420 2
                    $value = $locationService->loadLocation($content->contentInfo->mainLocationId)->pathString;
421 2
                    break;
422 4
                case 'publication_date':
423 1
                    $value = $content->contentInfo->publishedDate->getTimestamp();
424 1
                    break;
425 4
                case 'section_id':
426 1
                    $value = $content->contentInfo->sectionId;
427 1
                    break;
428 4
                case 'section_identifier':
429 1
                    $sectionService = $this->repository->getSectionService();
430 1
                    $value = $sectionService->loadSection($content->contentInfo->sectionId)->identifier;
431 1
                    break;
432 3
                case 'version_count':
433 1
                    $contentService = $this->repository->getContentService();
434 1
                    $value = count($contentService->loadVersions($content->contentInfo));
435 1
                    break;
436
                default:
437 2
                    if (strpos($reference['attribute'], 'object_state.') === 0) {
438 1
                        $stateGroupKey = substr($reference['attribute'], 13);
439 1
                        $stateGroup = $this->objectStateGroupMatcher->matchOneByKey($stateGroupKey);
440 1
                        $value = $stateGroupKey . '/' . $this->repository->getObjectStateService()->
441 1
                            getContentState($content->contentInfo, $stateGroup)->identifier;
442 1
                        break;
443
                    }
444
445
                    // allow to get the value of fields as well as their sub-parts
446 1
                    if (strpos($reference['attribute'], 'attributes.') === 0) {
447 1
                        $contentType = $this->repository->getContentTypeService()->loadContentType(
448 1
                            $content->contentInfo->contentTypeId
449
                        );
450 1
                        $parts = explode('.', $reference['attribute']);
451
                        // totally not sure if this list of special chars is correct for what could follow a jmespath identifier...
452
                        // also what about quoted strings?
453 1
                        $fieldIdentifier = preg_replace('/[[(|&!{].*$/', '', $parts[1]);
454 1
                        $field = $content->getField($fieldIdentifier);
455 1
                        $fieldDefinition = $contentType->getFieldDefinition($fieldIdentifier);
456 1
                        $hashValue = $this->fieldHandlerManager->fieldValueToHash(
457 1
                            $fieldDefinition->fieldTypeIdentifier, $contentType->identifier, $field->value
458
                        );
459 1
                        if (is_array($hashValue) ) {
460 1 View Code Duplication
                            if (count($parts) == 2 && $fieldIdentifier === $parts[1]) {
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...
461
                                throw new \InvalidArgumentException('Content Manager does not support setting references for attribute ' . $reference['attribute'] . ': the given attribute has an array value');
462
                            }
463 1
                            $value = JmesPath::search(implode('.', array_slice($parts, 1)), array($fieldIdentifier => $hashValue));
464
                        } else {
465
                            if (count($parts) > 2) {
466
                                throw new \InvalidArgumentException('Content Manager does not support setting references for attribute ' . $reference['attribute'] . ': the given attribute has a scalar value');
467
                            }
468
                            $value = $hashValue;
469
                        }
470 1
                        break;
471
                    }
472
473
                    throw new \InvalidArgumentException('Content Manager does not support setting references for attribute ' . $reference['attribute']);
474
            }
475
476 8
            $overwrite = false;
477 8
            if (isset($reference['overwrite'])) {
478
                $overwrite = $reference['overwrite'];
479
            }
480 8
            $this->referenceResolver->addReference($reference['identifier'], $value, $overwrite);
481
        }
482
483 8
        return true;
484
    }
485
486
    /**
487
     * @param array $matchCondition
488
     * @param string $mode
489
     * @param array $context
490
     * @throws \Exception
491
     * @return array
492
     *
493
     * @todo add support for dumping all object languages
494
     * @todo add 2ndary locations when in 'update' mode
495
     * @todo add dumping of sort_field and sort_order for 2ndary locations
496
     */
497 3
    public function generateMigration(array $matchCondition, $mode, array $context = array())
498
    {
499 3
        $previousUserId = $this->loginUser($this->getAdminUserIdentifierFromContext($context));
500 3
        $contentCollection = $this->contentMatcher->match($matchCondition);
501 3
        $data = array();
502
503
        /** @var \eZ\Publish\API\Repository\Values\Content\Content $content */
504 3
        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...
505
506 3
            $location = $this->repository->getLocationService()->loadLocation($content->contentInfo->mainLocationId);
507 3
            $contentType = $this->repository->getContentTypeService()->loadContentType(
508 3
                $content->contentInfo->contentTypeId
509
            );
510
511
            $contentData = array(
512 3
                'type' => reset($this->supportedStepTypes),
513 3
                'mode' => $mode
514
            );
515
516
            switch ($mode) {
517 3
                case 'create':
518 1
                    $contentData = array_merge(
519 1
                        $contentData,
520
                        array(
521 1
                            'content_type' => $contentType->identifier,
522 1
                            'parent_location' => $location->parentLocationId,
523 1
                            'priority' => $location->priority,
524 1
                            'is_hidden' => $location->invisible,
525 1
                            'sort_field' => $this->sortConverter->sortField2Hash($location->sortField),
526 1
                            'sort_order' => $this->sortConverter->sortOrder2Hash($location->sortOrder),
527 1
                            'remote_id' => $content->contentInfo->remoteId,
528 1
                            'location_remote_id' => $location->remoteId
529
                        )
530
                    );
531 1
                    $locationService = $this->repository->getLocationService();
532 1
                    $locations = $locationService->loadLocations($content->contentInfo);
533 1
                    if (count($locations) > 1) {
534
                        $otherParentLocations = array();
535
                        foreach($locations as $otherLocation) {
536
                            if ($otherLocation->id != $location->id) {
537
                                $otherParentLocations[] = $otherLocation->parentLocationId;
538
                            }
539
                        }
540
                        $contentData['other_parent_locations'] = $otherParentLocations;
541
                    }
542 1
                    break;
543 2 View Code Duplication
                case 'update':
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...
544 1
                    $contentData = array_merge(
545 1
                        $contentData,
546
                        array(
547
                            'match' => array(
548 1
                                ContentMatcher::MATCH_CONTENT_REMOTE_ID => $content->contentInfo->remoteId
549
                            ),
550 1
                            'new_remote_id' => $content->contentInfo->remoteId,
551
                        )
552
                    );
553 1
                    break;
554 1 View Code Duplication
                case 'delete':
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...
555 1
                    $contentData = array_merge(
556 1
                        $contentData,
557
                        array(
558
                            'match' => array(
559 1
                                ContentMatcher::MATCH_CONTENT_REMOTE_ID => $content->contentInfo->remoteId
560
                            )
561
                        )
562
                    );
563 1
                    break;
564
                default:
565
                    throw new \Exception("Executor 'content' doesn't support mode '$mode'");
566
            }
567
568 3
            if ($mode != 'delete') {
569
570 2
                $attributes = array();
571 2
                foreach ($content->getFieldsByLanguage($this->getLanguageCodeFromContext($context)) as $fieldIdentifier => $field) {
572 2
                    $fieldDefinition = $contentType->getFieldDefinition($fieldIdentifier);
573 2
                    $attributes[$field->fieldDefIdentifier] = $this->fieldHandlerManager->fieldValueToHash(
574 2
                        $fieldDefinition->fieldTypeIdentifier, $contentType->identifier, $field->value
575
                    );
576
                }
577
578 2
                $contentData = array_merge(
579 2
                    $contentData,
580
                    array(
581 2
                        'lang' => $this->getLanguageCodeFromContext($context),
582 2
                        'section' => $content->contentInfo->sectionId,
583 2
                        'owner' => $content->contentInfo->ownerId,
584 2
                        'modification_date' => $content->contentInfo->modificationDate->getTimestamp(),
585 2
                        'publication_date' => $content->contentInfo->publishedDate->getTimestamp(),
586 2
                        'always_available' => (bool)$content->contentInfo->alwaysAvailable,
587 2
                        'attributes' => $attributes
588
                    )
589
                );
590
            }
591
592 3
            $data[] = $contentData;
593
        }
594
595 3
        $this->loginUser($previousUserId);
596 3
        return $data;
597
    }
598
599
    /**
600
     * Helper function to set the fields of a ContentCreateStruct based on the DSL attribute settings.
601
     *
602
     * @param ContentCreateStruct|ContentUpdateStruct $createOrUpdateStruct
603
     * @param array $fields see description of expected format in code below
604
     * @param ContentType $contentType
605
     * @param $step
606
     * @throws \Exception
607
     */
608 11
    protected function setFields($createOrUpdateStruct, array $fields, ContentType $contentType, $step)
609
    {
610 11
        $i = 0;
611
        // the 'easy' yml: key = field name, value = value
612
        // deprecated: the 'legacy' yml: key = numerical index, value = array ( field name => value )
613 11
        foreach ($fields as $key => $field) {
614
615 11
            if ($key === $i && is_array($field) && count($field) == 1) {
616
                // each $field is one key value pair
617
                // eg.: $field = array($fieldIdentifier => $fieldValue)
0 ignored issues
show
Unused Code Comprehensibility introduced by
48% 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...
618 9
                reset($field);
619 9
                $fieldIdentifier = key($field);
620 9
                $fieldValue = $field[$fieldIdentifier];
621
            } else {
622 3
                $fieldIdentifier = $key;
623 3
                $fieldValue = $field;
624
            }
625
626 11
            if (!isset($contentType->fieldDefinitionsByIdentifier[$fieldIdentifier])) {
0 ignored issues
show
Bug introduced by
The property fieldDefinitionsByIdentifier does not seem to exist. Did you mean fieldDefinitions?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
627
                throw new \Exception("Field '$fieldIdentifier' is not present in content type '{$contentType->identifier}'");
628
            }
629
630 11
            $fieldDefinition = $contentType->fieldDefinitionsByIdentifier[$fieldIdentifier];
0 ignored issues
show
Bug introduced by
The property fieldDefinitionsByIdentifier does not seem to exist. Did you mean fieldDefinitions?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
631 11
            $fieldValue = $this->getFieldValue($fieldValue, $fieldDefinition, $contentType->identifier, $step->context);
632
633 11
            $createOrUpdateStruct->setField($fieldIdentifier, $fieldValue, $this->getLanguageCode($step));
634
635 11
            $i++;
636
        }
637 11
    }
638
639 1 View Code Duplication
    protected function setSection(Content $content, $sectionKey)
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...
640
    {
641 1
        $sectionKey = $this->referenceResolver->resolveReference($sectionKey);
642 1
        $section = $this->sectionMatcher->matchOneByKey($sectionKey);
643
644 1
        $sectionService = $this->repository->getSectionService();
645 1
        $sectionService->assignSection($content->contentInfo, $section);
646 1
    }
647
648 2
    protected function setObjectStates(Content $content, array $stateKeys)
649
    {
650 2
        foreach ($stateKeys as $stateKey) {
651 2
            $stateKey = $this->referenceResolver->resolveReference($stateKey);
652
            /** @var \eZ\Publish\API\Repository\Values\ObjectState\ObjectState $state */
653 2
            $state = $this->objectStateMatcher->matchOneByKey($stateKey);
654
655 2
            $stateService = $this->repository->getObjectStateService();
656 2
            $stateService->setContentState($content->contentInfo, $state->getObjectStateGroup(), $state);
657
        }
658 2
    }
659
660 1
    protected function setMainLocation(Content $content, $locationId)
661
    {
662 1
        $locationId = $this->referenceResolver->resolveReference($locationId);
663 1
        if (is_int($locationId) || ctype_digit($locationId)) {
664 1
            $location = $this->repository->getLocationService()->loadLocation($locationId);
665
        } else {
666
            $location = $this->repository->getLocationService()->loadLocationByRemoteId($locationId);
667
        }
668
669 1
        if ($location->contentInfo->id != $content->id) {
670
            throw new \Exception("Can not set main location {$location->id} to content {$content->id} as it belongs to another object");
671
        }
672
673 1
        $contentService = $this->repository->getContentService();
674 1
        $contentMetaDataUpdateStruct = $contentService->newContentMetadataUpdateStruct();
675 1
        $contentMetaDataUpdateStruct->mainLocationId = $location->id;
676 1
        $contentService->updateContentMetadata($location->contentInfo, $contentMetaDataUpdateStruct);
677 1
    }
678
679
    /**
680
     * Create the field value from the migration definition hash
681
     *
682
     * @param mixed $value
683
     * @param FieldDefinition $fieldDefinition
684
     * @param string $contentTypeIdentifier
685
     * @param array $context
686
     * @throws \InvalidArgumentException
687
     * @return mixed
688
     */
689 11
    protected function getFieldValue($value, FieldDefinition $fieldDefinition, $contentTypeIdentifier, array $context = array())
690
    {
691 11
        $fieldTypeIdentifier = $fieldDefinition->fieldTypeIdentifier;
692 11
        if (is_array($value) || $this->fieldHandlerManager->managesField($fieldTypeIdentifier, $contentTypeIdentifier)) {
693
            // inject info about the current content type and field into the context
694 3
            $context['contentTypeIdentifier'] = $contentTypeIdentifier;
695 3
            $context['fieldIdentifier'] = $fieldDefinition->identifier;
696 3
            return $this->fieldHandlerManager->hashToFieldValue($fieldTypeIdentifier, $contentTypeIdentifier, $value, $context);
697
        }
698
699 11
        return $this->getSingleFieldValue($value, $fieldDefinition, $contentTypeIdentifier, $context);
700
    }
701
702
    /**
703
     * Create the field value for a primitive field from the migration definition hash
704
     *
705
     * @param mixed $value
706
     * @param FieldDefinition $fieldDefinition
707
     * @param string $contentTypeIdentifier
708
     * @param array $context
709
     * @throws \InvalidArgumentException
710
     * @return mixed
711
     */
712 11
    protected function getSingleFieldValue($value, FieldDefinition $fieldDefinition, $contentTypeIdentifier, array $context = array())
0 ignored issues
show
Unused Code introduced by
The parameter $fieldDefinition is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $contentTypeIdentifier is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $context is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
713
    {
714
        // booleans were handled here. They are now handled as complextypes
715
716
        // q: do we really want this to happen by default on all scalar field values?
717
        // Note: if you want this *not* to happen, register a complex field for your scalar field...
718 11
        $value = $this->referenceResolver->resolveReference($value);
719
720 11
        return $value;
721
    }
722
723
    /**
724
     * Load user using either login, email, id - resolving eventual references
725
     * @param int|string $userKey
726
     * @return \eZ\Publish\API\Repository\Values\User\User
727
     */
728 2
    protected function getUser($userKey)
729
    {
730 2
        $userKey = $this->referenceResolver->resolveReference($userKey);
731 2
        return $this->userMatcher->matchOneByKey($userKey);
732
    }
733
734
    /**
735
     * @param int|string $date if integer, we assume a timestamp
736
     * @return \DateTime
737
     */
738 1
    protected function toDateTime($date)
739
    {
740 1
        if (is_int($date)) {
741
            return new \DateTime("@" . $date);
742
        } else {
743 1
            return new \DateTime($date);
744
        }
745
    }
746
}
747