Completed
Push — master ( b4efa6...174a17 )
by Gaetano
09:08
created

ContentManager::update()   F

Complexity

Conditions 19
Paths 1058

Size

Total Lines 82
Code Lines 45

Duplication

Lines 4
Ratio 4.88 %

Code Coverage

Tests 39
CRAP Score 19.5292

Importance

Changes 0
Metric Value
dl 4
loc 82
ccs 39
cts 44
cp 0.8864
rs 2.1041
c 0
b 0
f 0
cc 19
eloc 45
nc 1058
nop 0
crap 19.5292

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use eZ\Publish\API\Repository\Values\ContentType\ContentType;
6
use eZ\Publish\API\Repository\Values\ContentType\FieldDefinition;
7
use eZ\Publish\API\Repository\Values\Content\Content;
8
use eZ\Publish\API\Repository\Values\Content\ContentCreateStruct;
9
use eZ\Publish\API\Repository\Values\Content\ContentUpdateStruct;
10
use eZ\Publish\Core\FieldType\Checkbox\Value as CheckboxValue;
11
use Kaliop\eZMigrationBundle\API\Collection\ContentCollection;
12
use Kaliop\eZMigrationBundle\API\MigrationGeneratorInterface;
13
use Kaliop\eZMigrationBundle\Core\ComplexField\ComplexFieldManager;
14
use Kaliop\eZMigrationBundle\Core\Matcher\ContentMatcher;
15
use Kaliop\eZMigrationBundle\Core\Matcher\SectionMatcher;
16
use Kaliop\eZMigrationBundle\Core\Matcher\UserMatcher;
17
use Kaliop\eZMigrationBundle\Core\Matcher\ObjectStateMatcher;
18
use eZ\Publish\Core\Base\Exceptions\NotFoundException;
19
20
/**
21
 * Implements the actions for managing (create/update/delete) Content in the system through
22
 * migrations and abstracts away the eZ Publish Public API.
23
 *
24
 * @todo add support for updating of content metadata
25
 */
26
class ContentManager extends RepositoryExecutor implements MigrationGeneratorInterface
27 20
{
28
    protected $supportedStepTypes = array('content');
29 20
30 20
    protected $contentMatcher;
31 20
    protected $sectionMatcher;
32
    protected $userMatcher;
33
    protected $objectStateMatcher;
34
    protected $complexFieldManager;
35
    protected $locationManager;
36 4
37
    public function __construct(
38 4
        ContentMatcher $contentMatcher,
39 4
        SectionMatcher $sectionMatcher,
40 4
        UserMatcher $userMatcher,
41
        ObjectStateMatcher $objectStateMatcher,
42 4
        ComplexFieldManager $complexFieldManager,
43 4
        LocationManager $locationManager
44 3
    ) {
45 3
        $this->contentMatcher = $contentMatcher;
46 4
        $this->sectionMatcher = $sectionMatcher;
47
        $this->userMatcher = $userMatcher;
48 4
        $this->objectStateMatcher = $objectStateMatcher;
49 4
        $this->complexFieldManager = $complexFieldManager;
50
        $this->locationManager = $locationManager;
51 4
    }
52 1
53 1
    /**
54
     * Handle the content create migration action type
55
     */
56 4
    protected function create()
57 4
    {
58 1
        $contentService = $this->repository->getContentService();
59 1
        $locationService = $this->repository->getLocationService();
60 4
        $contentTypeService = $this->repository->getContentTypeService();
61 4
62 1
        $contentTypeIdentifier = $this->dsl['content_type'];
63 1
        $contentTypeIdentifier = $this->referenceResolver->resolveReference($contentTypeIdentifier);
64
        /// @todo use a contenttypematcher
65 4
        $contentType = $contentTypeService->loadContentTypeByIdentifier($contentTypeIdentifier);
66 1
67 1
        $contentCreateStruct = $contentService->newContentCreateStruct($contentType, $this->getLanguageCode());
68
69 4
        $this->setFields($contentCreateStruct, $this->dsl['attributes'], $contentType);
70
71 4
        if (isset($this->dsl['always_available'])) {
72
            $contentCreateStruct->alwaysAvailable = $this->dsl['always_available'];
73
        } else {
74
            // Could be removed when https://github.com/ezsystems/ezpublish-kernel/pull/1874 is merged,
75
            // but we strive to support old eZ kernel versions as well...
76
            $contentCreateStruct->alwaysAvailable = $contentType->defaultAlwaysAvailable;
77
        }
78
79
        if (isset($this->dsl['remote_id'])) {
80
            $contentCreateStruct->remoteId = $this->dsl['remote_id'];
81
        }
82
83 4
        if (isset($this->dsl['section'])) {
84 3
            $sectionId = $this->dsl['section'];
85
            $sectionId = $this->referenceResolver->resolveReference($sectionId);
86 3
            $contentCreateStruct->sectionId = $sectionId;
87 3
        }
88
89 View Code Duplication
        if (isset($this->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...
90
            $owner = $this->getUser($this->dsl['owner']);
91
            $contentCreateStruct->ownerId = $owner->id;
92
        }
93
94 1
        // This is a bit tricky, as the eZPublish API does not support having a different creator and owner with only 1 version.
95
        // We allow it, hoping that nothing gets broken because of it
96 1
        if (isset($this->dsl['version_creator'])) {
97 1
            $realContentOwnerId = $contentCreateStruct->ownerId;
98
            if ($realContentOwnerId == null) {
99
                $realContentOwnerId = $this->repository->getCurrentUser()->id;
100
            }
101
            $versionCreator = $this->getUser($this->dsl['version_creator']);
102
            $contentCreateStruct->ownerId = $versionCreator->id;
103
        }
104
105
        if (isset($this->dsl['modification_date'])) {
106
            $contentCreateStruct->modificationDate = $this->toDateTime($this->dsl['modification_date']);
107
        }
108
109
        // instantiate a location create struct from the parent location:
110
        // BC
111
        $locationId = isset($this->dsl['parent_location']) ? $this->dsl['parent_location'] : (
112
            isset($this->dsl['main_location']) ? $this->dsl['main_location'] : null
113
        );
114
        // 1st resolve references
115
        $locationId = $this->referenceResolver->resolveReference($locationId);
116
        // 2nd allow to specify the location via remote_id
117
        $locationId = $this->locationManager->matchLocationByKey($locationId)->id;
118
        $locationCreateStruct = $locationService->newLocationCreateStruct($locationId);
119
120
        if (isset($this->dsl['location_remote_id'])) {
121 1
            $locationCreateStruct->remoteId = $this->dsl['location_remote_id'];
122
        }
123 1
124
        if (isset($this->dsl['priority'])) {
125
            $locationCreateStruct->priority = $this->dsl['priority'];
126
        }
127 1
128
        if (isset($this->dsl['is_hidden'])) {
129 1
            $locationCreateStruct->hidden = $this->dsl['is_hidden'];
130 1
        }
131
132 1
        if (isset($this->dsl['sort_field'])) {
133 1
            $locationCreateStruct->sortField = $this->locationManager->getSortField($this->dsl['sort_field']);
134 1
        } else {
135
            $locationCreateStruct->sortField = $contentType->defaultSortField;
136 1
        }
137
138 1
        if (isset($this->dsl['sort_order'])) {
139 1
            $locationCreateStruct->sortOrder = $this->locationManager->getSortOrder($this->dsl['sort_order']);
140 1
        } else {
141
            $locationCreateStruct->sortOrder = $contentType->defaultSortOrder;
142 1
        }
143 1
144 1
        $locations = array($locationCreateStruct);
145
146 1
        // BC
147
        $other_locations = isset($this->dsl['other_parent_locations']) ? $this->dsl['other_parent_locations'] : (
148
            isset($this->dsl['other_locations']) ? $this->dsl['other_locations'] : null
149
        );
150
        if (isset($other_locations)) {
151
            foreach ($other_locations as $locationId) {
152
                $locationId = $this->referenceResolver->resolveReference($locationId);
153
                $locationId = $this->locationManager->matchLocationByKey($locationId)->id;
154
                $secondaryLocationCreateStruct = $locationService->newLocationCreateStruct($locationId);
155
                array_push($locations, $secondaryLocationCreateStruct);
156
            }
157
        }
158
159
        // create a draft using the content and location create struct and publish it
160
        $draft = $contentService->createContent($contentCreateStruct, $locations);
161 1
        $content = $contentService->publishVersion($draft->versionInfo);
162 1
163 1
        if (isset($this->dsl['object_states'])) {
164
            $this->setObjectStates($content, $this->dsl['object_states']);
165
        }
166
167
        // 2nd part of the hack: re-set the content owner to its intended value
168 3
        if (isset($this->dsl['version_creator']) || isset($this->dsl['publication_date'])) {
169
            $contentMetaDataUpdateStruct = $contentService->newContentMetadataUpdateStruct();
170 3
171
            if (isset($this->dsl['version_creator'])) {
172 3
                $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...
173
            }
174 3
            if (isset($this->dsl['publication_date'])) {
175
                $contentMetaDataUpdateStruct->publishedDate = $this->toDateTime($this->dsl['publication_date']);
176 3
            }
177 3
178
            $contentService->updateContentMetadata($content->contentInfo, $contentMetaDataUpdateStruct);
179
        }
180
181 3
        $this->setReferences($content);
182 3
183
        return $content;
184
    }
185
186
    /**
187
     * Handle the content update migration action type
188
     *
189 3
     * @todo handle updating of more metadata fields
190
     */
191 3
    protected function update()
192
    {
193
        $contentService = $this->repository->getContentService();
194
        $contentTypeService = $this->repository->getContentTypeService();
195
196 3
        $contentCollection = $this->matchContents('update');
197 1
198 1
        if (count($contentCollection) > 1 && isset($this->dsl['references'])) {
199 1
            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");
200
        }
201
202 1
        $contentType = null;
203
204 3
        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...
205
            $contentInfo = $content->contentInfo;
206
207 3
            if ($contentType == null) {
208 3
                $contentType = $contentTypeService->loadContentType($contentInfo->contentTypeId);
209 1
            }
210 1
211 1
            $contentUpdateStruct = $contentService->newContentUpdateStruct();
212 1
213 1
            if (isset($this->dsl['attributes'])) {
214 1
                $this->setFields($contentUpdateStruct, $this->dsl['attributes'], $contentType);
215 3
            }
216 3
217 3
            $versionCreator = null;
218
            if (isset($this->dsl['version_creator'])) {
219 3
                $versionCreator = $this->getUser($this->dsl['version_creator']);
220
            }
221 3
222
            $draft = $contentService->createContentDraft($contentInfo, null, $versionCreator);
223
            $contentService->updateContent($draft->versionInfo, $contentUpdateStruct);
224
            $content = $contentService->publishVersion($draft->versionInfo);
225
226
            if (isset($this->dsl['always_available']) ||
227
                isset($this->dsl['new_remote_id']) ||
228
                isset($this->dsl['owner']) ||
229
                isset($this->dsl['modification_date']) ||
230
                isset($this->dsl['publication_date'])) {
231 4
232
                $contentMetaDataUpdateStruct = $contentService->newContentMetadataUpdateStruct();
233 4
234
                if (isset($this->dsl['always_available'])) {
235
                    $contentMetaDataUpdateStruct->alwaysAvailable = $this->dsl['always_available'];
236 4
                }
237
238 4
                if (isset($this->dsl['new_remote_id'])) {
239
                    $contentMetaDataUpdateStruct->remoteId = $this->dsl['new_remote_id'];
240 4
                }
241
242 1 View Code Duplication
                if (isset($this->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...
243 1
                    $owner = $this->getUser($this->dsl['owner']);
244
                    $contentMetaDataUpdateStruct->ownerId = $owner->id;
245 4
                }
246 3
247
                if (isset($this->dsl['modification_date'])) {
248 4
                    $contentMetaDataUpdateStruct->modificationDate = $this->toDateTime($this->dsl['modification_date']);
249 4
                }
250 4
251
                if (isset($this->dsl['publication_date'])) {
252
                    $contentMetaDataUpdateStruct->publishedDate = $this->toDateTime($this->dsl['publication_date']);
253
                }
254
255
                $content = $contentService->updateContentMetadata($content->contentInfo, $contentMetaDataUpdateStruct);
256
            }
257
258
            if (isset($this->dsl['section'])) {
259
                $this->setSection($content, $this->dsl['section']);
260
            }
261
262 4
            if (isset($this->dsl['object_states'])) {
263
                $this->setObjectStates($content, $this->dsl['object_states']);
264 4
            }
265 4
266
            $contentCollection[$key] = $content;
267
        }
268 4
269 4
        $this->setReferences($contentCollection);
0 ignored issues
show
Bug introduced by
It seems like $contentCollection defined by $this->matchContents('update') on line 196 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...
270 4
271
        return $contentCollection;
272 4
    }
273 1
274 1
    /**
275
     * Handle the content delete migration action type
276 4
     */
277
    protected function delete()
278
    {
279
        $contentService = $this->repository->getContentService();
280
281
        $contentCollection = $this->matchContents('delete');
282
283
        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...
284
            try {
285
                $contentService->deleteContent($content->contentInfo);
286
            } catch (NotFoundException $e) {
287 1
                // Someone else (or even us, by virtue of location tree?) removed the content which we found just a
288
                // second ago. We can safely ignore this
289 1
            }
290 1
        }
291
292
        return $contentCollection;
293
    }
294
295
    /**
296
     * @param string $action
297
     * @return ContentCollection
298
     * @throws \Exception
299
     */
300 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...
301
    {
302 3
        if (!isset($this->dsl['object_id']) && !isset($this->dsl['remote_id']) && !isset($this->dsl['match'])) {
303
            throw new \Exception("The ID or remote ID of an object or a Match Condition is required to $action a new location.");
304 3
        }
305 2
306
        // Backwards compat
307
        if (!isset($this->dsl['match'])) {
308 3
            if (isset($this->dsl['object_id'])) {
309
                $this->dsl['match'] = array('content_id' => $this->dsl['object_id']);
310
            } elseif (isset($this->dsl['remote_id'])) {
311
                $this->dsl['match'] = array('content_remote_id' => $this->dsl['remote_id']);
312
            }
313
        }
314
315 3
        $match = $this->dsl['match'];
316
317 3
        // convert the references passed in the match
318 3
        foreach ($match as $condition => $values) {
319 3
            if (is_array($values)) {
320 3
                foreach ($values as $position => $value) {
321 3
                    $match[$condition][$position] = $this->referenceResolver->resolveReference($value);
322 3
                }
323 2
            } else {
324 2
                $match[$condition] = $this->referenceResolver->resolveReference($values);
325 2
            }
326 1
        }
327 1
328 1
        return $this->contentMatcher->match($match);
329 1
    }
330
331
    /**
332
     * Helper function to set the fields of a ContentCreateStruct based on the DSL attribute settings.
333 3
     *
334
     * @param ContentCreateStruct|ContentUpdateStruct $createOrUpdateStruct
335 3
     * @param ContentType $contentType
336 3
     * @param array $fields see description of expected format in code below
337
     * @throws \Exception
338 3
     */
339
    protected function setFields($createOrUpdateStruct, array $fields, ContentType $contentType)
340
    {
341
        $i = 0;
342
        // the 'easy' yml: key = field name, value = value
343
        // deprecated: the 'legacy' yml: key = numerical index, value = array ( field name => value )
344
        foreach ($fields as $key => $field) {
345
346
            if ($key === $i && is_array($field) && count($field) == 1) {
347
                // each $field is one key value pair
348
                // 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...
349
                reset($field);
350
                $fieldIdentifier = key($field);
351
                $fieldValue = $field[$fieldIdentifier];
352
            } else {
353
                $fieldIdentifier = $key;
354
                $fieldValue = $field;
355
            }
356
357
            if (!isset($contentType->fieldDefinitionsByIdentifier[$fieldIdentifier])) {
0 ignored issues
show
Bug introduced by
The property fieldDefinitionsByIdentifier does not seem to exist. Did you mean identifier?

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...
358
                throw new \Exception("Field '$fieldIdentifier' is not present in field type '{$contentType->identifier}'");
359
            }
360
361
            $fieldDefinition = $contentType->fieldDefinitionsByIdentifier[$fieldIdentifier];
0 ignored issues
show
Bug introduced by
The property fieldDefinitionsByIdentifier does not seem to exist. Did you mean identifier?

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...
362
            $fieldValue = $this->getFieldValue($fieldValue, $fieldDefinition, $contentType->identifier, $this->context);
363
364
            $createOrUpdateStruct->setField($fieldIdentifier, $fieldValue, $this->getLanguageCode());
365
366
            $i++;
367
        }
368
    }
369
370
    protected function setSection(Content $content, $sectionKey)
371
    {
372
        $sectionKey = $this->referenceResolver->resolveReference($sectionKey);
373
        $section = $this->sectionMatcher->matchOneByKey($sectionKey);
374
375
        $sectionService = $this->repository->getSectionService();
376
        $sectionService->assignSection($content->contentInfo, $section);
377
    }
378
379
    protected function setObjectStates(Content $content, array $stateKeys)
380
    {
381
        foreach ($stateKeys as $stateKey) {
382
            $stateKey = $this->referenceResolver->resolveReference($stateKey);
383
            /** @var \eZ\Publish\API\Repository\Values\ObjectState\ObjectState $state */
384
            $state = $this->objectStateMatcher->matchOneByKey($stateKey);
385
386
            $stateService = $this->repository->getObjectStateService();
387
            $stateService->setContentState($content->contentInfo, $state->getObjectStateGroup(), $state);
388
        }
389
    }
390
391
    /**
392
     * Create the field value for either a primitive (ie. scalar) or complex field
393
     *
394
     * @param mixed $value
395
     * @param FieldDefinition $fieldDefinition
396
     * @param string $contentTypeIdentifier
397
     * @param array $context
398
     * @throws \InvalidArgumentException
399
     * @return mixed
400
     */
401
    protected function getFieldValue($value, FieldDefinition $fieldDefinition, $contentTypeIdentifier, array $context = array())
402
    {
403
        $fieldTypeIdentifier = $fieldDefinition->fieldTypeIdentifier;
404
        if (is_array($value) || $this->complexFieldManager->managesField($fieldTypeIdentifier, $contentTypeIdentifier)) {
405
            return $this->complexFieldManager->getComplexFieldValue($fieldTypeIdentifier, $contentTypeIdentifier, $value, $context);
406
        }
407
408
        return $this->getSingleFieldValue($value, $fieldDefinition, $contentTypeIdentifier, $context);
409
    }
410
411
    /**
412
     * Create the field value for a primitive field
413
     * This function is needed to get past validation on Checkbox fieldtype (eZP bug)
414
     *
415
     * @param mixed $value
416
     * @param FieldDefinition $fieldDefinition
417
     * @param string $contentTypeIdentifier
418
     * @param array $context
419
     * @throws \InvalidArgumentException
420
     * @return mixed
421
     */
422
    protected function getSingleFieldValue($value, FieldDefinition $fieldDefinition, $contentTypeIdentifier, array $context = array())
0 ignored issues
show
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...
423
    {
424
        $fieldTypeIdentifier = $fieldDefinition->fieldTypeIdentifier;
425
        switch ($fieldTypeIdentifier) {
426
            case 'ezboolean':
427
                $value = new CheckboxValue(($value == 1) ? true : false);
428
                break;
429
            default:
430
                // do nothing
431
        }
432
433
        // q: do we really want this to happen by default on all scalar field values?
434
        // Note: if you want this *not* to happen, register a complex field for your scalar field...
435
        $value = $this->referenceResolver->resolveReference($value);
436
437
        return $value;
438
    }
439
440
    /**
441
     * Load user using either login, email, id - resolving eventual references
442
     * @param int|string $userKey
443
     * @return \eZ\Publish\API\Repository\Values\User\User
444
     */
445
    protected function getUser($userKey)
446
    {
447
        $userKey = $this->referenceResolver->resolveReference($userKey);
448
        return $this->userMatcher->matchOneByKey($userKey);
449
    }
450
451
    /**
452
     * Sets references to certain content attributes.
453
     * The Content Manager currently supports setting references to object_id and location_id
454
     *
455
     * @param \eZ\Publish\API\Repository\Values\Content\Content|ContentCollection $content
456
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute
457
     * @return boolean
458
     *
459
     * @todo add support for other attributes: remote ids, contentTypeId, contentTypeIdentifier, section, etc...
460
     */
461
    protected function setReferences($content)
462
    {
463
        if (!array_key_exists('references', $this->dsl)) {
464
            return false;
465
        }
466
467
        if ($content instanceof ContentCollection) {
468
            if (count($content) > 1) {
469
                throw new \InvalidArgumentException('Content Manager does not support setting references for creating/updating of multiple contents');
470
            }
471
            $content = reset($content);
472
        }
473
474
        foreach ($this->dsl['references'] as $reference) {
475
476
            switch ($reference['attribute']) {
477
                case 'object_id':
478
                case 'content_id':
479
                case 'id':
480
                    $value = $content->id;
481
                    break;
482
                case 'remote_id':
483
                case 'content_remote_id':
484
                    $value = $content->contentInfo->remoteId;
485
                    break;
486
                case 'location_id':
487
                    $value = $content->contentInfo->mainLocationId;
488
                    break;
489
                case 'path':
490
                    $locationService = $this->repository->getLocationService();
491
                    $value = $locationService->loadLocation($content->contentInfo->mainLocationId)->pathString;
492
                    break;
493
                default:
494
                    throw new \InvalidArgumentException('Content Manager does not support setting references for attribute ' . $reference['attribute']);
495
            }
496
497
            $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...ver\ChainPrefixResolver, Kaliop\eZMigrationBundle...ver\ChainRegexpResolver, Kaliop\eZMigrationBundle...eResolver\ChainResolver, 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...
498
        }
499
500
        return true;
501
    }
502
503
    /**
504
     * @param int|string $date if integer, we assume a timestamp
505
     * @return \DateTime
506
     */
507
    protected function toDateTime($date)
508
    {
509
        if (is_int($date)) {
510
            return new \DateTime("@" . $date);
511
        } else {
512
            return new \DateTime($date);
513
        }
514
    }
515
516
    /**
517
     * @param string $matchType
518
     * @param string|string[] $matchValue
519
     * @param string $mode
520
     * @throws \Exception
521
     * @return array
522
     *
523
     * @todo add support for dumping all object languages
524
     */
525
    public function generateMigration($matchType, $matchValue, $mode)
526
    {
527
        $this->loginUser(self::ADMIN_USER_ID);
528
        $contentCollection = $this->contentMatcher->match(array($matchType => $matchValue));
529
        $data = array();
530
531
        /** @var \eZ\Publish\API\Repository\Values\Content\Content $content */
532
        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...
533
534
            $location = $this->repository->getLocationService()->loadLocation($content->contentInfo->mainLocationId);
535
            $contentType = $this->repository->getContentTypeService()->loadContentType(
536
                $content->contentInfo->contentTypeId
537
            );
538
            $fieldTypeService = $this->repository->getFieldTypeService();
539
540
            $contentData = array(
541
                'type' => 'content',
542
                'mode' => $mode
543
            );
544
545
            switch ($mode) {
546
                case 'create':
547
                    // @todo Add sort_field and sort_order
548
                    // @todo Add 2ndary locations
549
                    $contentData = array_merge(
550
                        $contentData,
551
                        array(
552
                            'content_type' => $contentType->identifier,
553
                            'parent_location' => $location->parentLocationId,
554
                            'priority' => $location->priority,
555
                            'is_hidden' => $location->invisible,
556
                            'remote_id' => $content->contentInfo->remoteId,
557
                            'location_remote_id' => $location->remoteId
558
                        )
559
                    );
560
                    break;
561
                case 'update':
562
                case 'delete':
563
                    $contentData = array_merge(
564
                        $contentData,
565
                        array(
566
                            'match' => array(
567
                                'content_remote_id' => $content->contentInfo->remoteId
568
                            )
569
                        )
570
                    );
571
                    break;
572
                default:
573
                    throw new \Exception("Executor 'content' doesn't support mode '$mode'");
574
            }
575
576
            if ($mode != 'delete') {
577
                $attributes = array();
578
                foreach ($content->getFieldsByLanguage($this->getLanguageCode()) as $field) {
579
                    $fieldDefinition = $contentType->getFieldDefinition($field->fieldDefIdentifier);
580
                    $fieldType = $fieldTypeService->getFieldType($fieldDefinition->fieldTypeIdentifier);
581
                    $attributes[$field->fieldDefIdentifier] = $fieldType->toHash($field->value);
582
                }
583
584
                $contentData = array_merge(
585
                    $contentData,
586
                    array(
587
                        'lang' => $this->getLanguageCode(),
588
                        'section' => $content->contentInfo->sectionId,
589
                        'owner' => $content->contentInfo->ownerId,
590
                        'modification_date' => $content->contentInfo->modificationDate,
591
                        'publication_date' => $content->contentInfo->publishedDate,
592
                        'always_available' => $content->contentInfo->alwaysAvailable,
593
                        'attributes' => $attributes
594
                    )
595
                );
596
            }
597
598
            $data[] = $contentData;
599
        }
600
601
        return $data;
602
    }
603
}
604