Completed
Pull Request — master (#93)
by
unknown
23:15
created

ContentManager::matchContents()   D

Complexity

Conditions 10
Paths 13

Size

Total Lines 30
Code Lines 16

Duplication

Lines 30
Ratio 100 %

Code Coverage

Tests 14
CRAP Score 11.097

Importance

Changes 0
Metric Value
dl 30
loc 30
ccs 14
cts 18
cp 0.7778
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 16
nc 13
nop 1
crap 11.097

How to fix   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
        }
74
75
        if (isset($this->dsl['remote_id'])) {
76
            $contentCreateStruct->remoteId = $this->dsl['remote_id'];
77
        }
78
79
        if (isset($this->dsl['section'])) {
80
            $sectionId = $this->dsl['section'];
81
            $sectionId = $this->referenceResolver->resolveReference($sectionId);
82
            $contentCreateStruct->sectionId = $sectionId;
83 4
        }
84 3
85 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...
86 3
            $owner = $this->getUser($this->dsl['owner']);
87 3
            $contentCreateStruct->ownerId = $owner->id;
88
        }
89
90
        // This is a bit tricky, as the eZPublish API does not support having a different creator and owner with only 1 version.
91
        // We allow it, hoping that nothing gets broken because of it
92
        if (isset($this->dsl['version_creator'])) {
93
            $realContentOwnerId = $contentCreateStruct->ownerId;
94 1
            if ($realContentOwnerId == null) {
95
                $realContentOwnerId = $this->repository->getCurrentUser()->id;
96 1
            }
97 1
            $versionCreator = $this->getUser($this->dsl['version_creator']);
98
            $contentCreateStruct->ownerId = $versionCreator->id;
99
        }
100
101
        if (isset($this->dsl['modification_date'])) {
102
            $contentCreateStruct->modificationDate = $this->toDateTime($this->dsl['modification_date']);
103
        }
104
105
        // instantiate a location create struct from the parent location:
106
        // BC
107
        $locationId = isset($this->dsl['parent_location']) ? $this->dsl['parent_location'] : (
108
            isset($this->dsl['main_location']) ? $this->dsl['main_location'] : null
109
        );
110
        // 1st resolve references
111
        $locationId = $this->referenceResolver->resolveReference($locationId);
112
        // 2nd allow to specify the location via remote_id
113
        $locationId = $this->locationManager->matchLocationByKey($locationId)->id;
114
        $locationCreateStruct = $locationService->newLocationCreateStruct($locationId);
115
116
        if (isset($this->dsl['location_remote_id'])) {
117
            $locationCreateStruct->remoteId = $this->dsl['location_remote_id'];
118
        }
119
120
        if (isset($this->dsl['priority'])) {
121 1
            $locationCreateStruct->priority = $this->dsl['priority'];
122
        }
123 1
124
        if (isset($this->dsl['is_hidden'])) {
125
            $locationCreateStruct->hidden = $this->dsl['is_hidden'];
126
        }
127 1
128
        if (isset($this->dsl['sort_field'])) {
129 1
            $locationCreateStruct->sortField = $this->locationManager->getSortField($this->dsl['sort_field']);
130 1
        } else {
131
            $locationCreateStruct->sortField = $contentType->defaultSortField;
132 1
        }
133 1
134 1
        if (isset($this->dsl['sort_order'])) {
135
            $locationCreateStruct->sortOrder = $this->locationManager->getSortOrder($this->dsl['sort_order']);
136 1
        } else {
137
            $locationCreateStruct->sortOrder = $contentType->defaultSortOrder;
138 1
        }
139 1
140 1
        $locations = array($locationCreateStruct);
141
142 1
        // BC
143 1
        $other_locations = isset($this->dsl['other_parent_locations']) ? $this->dsl['other_parent_locations'] : (
144 1
            isset($this->dsl['other_locations']) ? $this->dsl['other_locations'] : null
145
        );
146 1
        if (isset($other_locations)) {
147
            foreach ($other_locations as $locationId) {
148
                $locationId = $this->referenceResolver->resolveReference($locationId);
149
                $locationId = $this->locationManager->matchLocationByKey($locationId)->id;
150
                $secondaryLocationCreateStruct = $locationService->newLocationCreateStruct($locationId);
151
                array_push($locations, $secondaryLocationCreateStruct);
152
            }
153
        }
154
155
        // create a draft using the content and location create struct and publish it
156
        $draft = $contentService->createContent($contentCreateStruct, $locations);
157
        $content = $contentService->publishVersion($draft->versionInfo);
158
159
        if (isset($this->dsl['object_states'])) {
160
            $this->setObjectStates($content, $this->dsl['object_states']);
161 1
        }
162 1
163 1
        // 2nd part of the hack: re-set the content owner to its intended value
164
        if (isset($this->dsl['version_creator']) || isset($this->dsl['publication_date'])) {
165
            $contentMetaDataUpdateStruct = $contentService->newContentMetadataUpdateStruct();
166
167
            if (isset($this->dsl['version_creator'])) {
168 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...
169
            }
170 3
            if (isset($this->dsl['publication_date'])) {
171
                $contentMetaDataUpdateStruct->publishedDate = $this->toDateTime($this->dsl['publication_date']);
172 3
            }
173
174 3
            $contentService->updateContentMetadata($content->contentInfo, $contentMetaDataUpdateStruct);
175
        }
176 3
177 3
        $this->setReferences($content);
178
179
        return $content;
180
    }
181 3
182 3
    /**
183
     * Handle the content update migration action type
184
     *
185
     * @todo handle updating of more metadata fields
186
     */
187
    protected function update()
188
    {
189 3
        $contentService = $this->repository->getContentService();
190
        $contentTypeService = $this->repository->getContentTypeService();
191 3
192
        $contentCollection = $this->matchContents('update');
193
194
        if (count($contentCollection) > 1 && isset($this->dsl['references'])) {
195
            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");
196 3
        }
197 1
198 1
        $contentType = null;
199 1
200
        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...
201
            $contentInfo = $content->contentInfo;
202 1
203
            if ($contentType == null) {
204 3
                $contentType = $contentTypeService->loadContentType($contentInfo->contentTypeId);
205
            }
206
207 3
            $contentUpdateStruct = $contentService->newContentUpdateStruct();
208 3
209 1
            if (isset($this->dsl['attributes'])) {
210 1
                $this->setFields($contentUpdateStruct, $this->dsl['attributes'], $contentType);
211 1
            }
212 1
213 1
            $versionCreator = null;
214 1
            if (isset($this->dsl['version_creator'])) {
215 3
                $versionCreator = $this->getUser($this->dsl['version_creator']);
216 3
            }
217 3
218
            $draft = $contentService->createContentDraft($contentInfo, null, $versionCreator);
219 3
            $contentService->updateContent($draft->versionInfo, $contentUpdateStruct);
220
            $content = $contentService->publishVersion($draft->versionInfo);
221 3
222
            if (isset($this->dsl['always_available']) ||
223
                isset($this->dsl['new_remote_id']) ||
224
                isset($this->dsl['owner']) ||
225
                isset($this->dsl['modification_date']) ||
226
                isset($this->dsl['publication_date'])) {
227
228
                $contentMetaDataUpdateStruct = $contentService->newContentMetadataUpdateStruct();
229
230
                if (isset($this->dsl['always_available'])) {
231 4
                    $contentMetaDataUpdateStruct->alwaysAvailable = $this->dsl['always_available'];
232
                }
233 4
234
                if (isset($this->dsl['new_remote_id'])) {
235
                    $contentMetaDataUpdateStruct->remoteId = $this->dsl['new_remote_id'];
236 4
                }
237
238 4 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...
239
                    $owner = $this->getUser($this->dsl['owner']);
240 4
                    $contentMetaDataUpdateStruct->ownerId = $owner->id;
241
                }
242 1
243 1
                if (isset($this->dsl['modification_date'])) {
244
                    $contentMetaDataUpdateStruct->modificationDate = $this->toDateTime($this->dsl['modification_date']);
245 4
                }
246 3
247
                if (isset($this->dsl['publication_date'])) {
248 4
                    $contentMetaDataUpdateStruct->publishedDate = $this->toDateTime($this->dsl['publication_date']);
249 4
                }
250 4
251
                $content = $contentService->updateContentMetadata($content->contentInfo, $contentMetaDataUpdateStruct);
252
            }
253
254
            if (isset($this->dsl['section'])) {
255
                $this->setSection($content, $this->dsl['section']);
256
            }
257
258
            if (isset($this->dsl['object_states'])) {
259
                $this->setObjectStates($content, $this->dsl['object_states']);
260
            }
261
262 4
            $contentCollection[$key] = $content;
263
        }
264 4
265 4
        $this->setReferences($contentCollection);
0 ignored issues
show
Bug introduced by
It seems like $contentCollection defined by $this->matchContents('update') on line 192 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...
266
267
        return $contentCollection;
268 4
    }
269 4
270 4
    /**
271
     * Handle the content delete migration action type
272 4
     */
273 1
    protected function delete()
274 1
    {
275
        $contentService = $this->repository->getContentService();
276 4
277
        $contentCollection = $this->matchContents('delete');
278
279
        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...
280
            try {
281
                $contentService->deleteContent($content->contentInfo);
282
            } catch (NotFoundException $e) {
283
                // Someone else (or even us, by virtue of location tree?) removed the content which we found just a
284
                // second ago. We can safely ignore this
285
            }
286
        }
287 1
288
        return $contentCollection;
289 1
    }
290 1
291
    /**
292
     * @param string $action
293
     * @return ContentCollection
294
     * @throws \Exception
295
     */
296 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...
297
    {
298
        if (!isset($this->dsl['object_id']) && !isset($this->dsl['remote_id']) && !isset($this->dsl['match'])) {
299
            throw new \Exception("The ID or remote ID of an object or a Match Condition is required to $action a new location.");
300
        }
301
302 3
        // Backwards compat
303
        if (!isset($this->dsl['match'])) {
304 3
            if (isset($this->dsl['object_id'])) {
305 2
                $this->dsl['match'] = array('content_id' => $this->dsl['object_id']);
306
            } elseif (isset($this->dsl['remote_id'])) {
307
                $this->dsl['match'] = array('content_remote_id' => $this->dsl['remote_id']);
308 3
            }
309
        }
310
311
        $match = $this->dsl['match'];
312
313
        // convert the references passed in the match
314
        foreach ($match as $condition => $values) {
315 3
            if (is_array($values)) {
316
                foreach ($values as $position => $value) {
317 3
                    $match[$condition][$position] = $this->referenceResolver->resolveReference($value);
318 3
                }
319 3
            } else {
320 3
                $match[$condition] = $this->referenceResolver->resolveReference($values);
321 3
            }
322 3
        }
323 2
324 2
        return $this->contentMatcher->match($match);
325 2
    }
326 1
327 1
    /**
328 1
     * Helper function to set the fields of a ContentCreateStruct based on the DSL attribute settings.
329 1
     *
330
     * @param ContentCreateStruct|ContentUpdateStruct $createOrUpdateStruct
331
     * @param ContentType $contentType
332
     * @param array $fields see description of expected format in code below
333 3
     * @throws \Exception
334
     */
335 3
    protected function setFields($createOrUpdateStruct, array $fields, ContentType $contentType)
336 3
    {
337
        $i = 0;
338 3
        // the 'easy' yml: key = field name, value = value
339
        // deprecated: the 'legacy' yml: key = numerical index, value = array ( field name => value )
340
        foreach ($fields as $key => $field) {
341
342
            if ($key === $i && is_array($field) && count($field) == 1) {
343
                // each $field is one key value pair
344
                // 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...
345
                reset($field);
346
                $fieldIdentifier = key($field);
347
                $fieldValue = $field[$fieldIdentifier];
348
            } else {
349
                $fieldIdentifier = $key;
350
                $fieldValue = $field;
351
            }
352
353
            $fieldDefinition = $contentType->getFieldDefinition($fieldIdentifier);
354
355
            if ($fieldDefinition === null) {
356
                throw new \Exception("Field '$fieldIdentifier' is not present in content type '{$contentType->identifier}'");
357
            }
358
359
            $fieldValue = $this->getFieldValue($fieldValue, $fieldDefinition, $contentType->identifier, $this->context);
360
361
            $createOrUpdateStruct->setField($fieldIdentifier, $fieldValue, $this->getLanguageCode());
362
363
            $i++;
364
        }
365
    }
366
367
    protected function setSection(Content $content, $sectionKey)
368
    {
369
        $sectionKey = $this->referenceResolver->resolveReference($sectionKey);
370
        $section = $this->sectionMatcher->matchOneByKey($sectionKey);
371
372
        $sectionService = $this->repository->getSectionService();
373
        $sectionService->assignSection($content->contentInfo, $section);
374
    }
375
376
    protected function setObjectStates(Content $content, array $stateKeys)
377
    {
378
        foreach ($stateKeys as $stateKey) {
379
            $stateKey = $this->referenceResolver->resolveReference($stateKey);
380
            /** @var \eZ\Publish\API\Repository\Values\ObjectState\ObjectState $state */
381
            $state = $this->objectStateMatcher->matchOneByKey($stateKey);
382
383
            $stateService = $this->repository->getObjectStateService();
384
            $stateService->setContentState($content->contentInfo, $state->getObjectStateGroup(), $state);
385
        }
386
    }
387
388
    /**
389
     * Create the field value for either a primitive (ie. scalar) or complex field
390
     *
391
     * @param mixed $value
392
     * @param FieldDefinition $fieldDefinition
393
     * @param string $contentTypeIdentifier
394
     * @param array $context
395
     * @throws \InvalidArgumentException
396
     * @return mixed
397
     */
398
    protected function getFieldValue($value, FieldDefinition $fieldDefinition, $contentTypeIdentifier, array $context = array())
399
    {
400
        $fieldTypeIdentifier = $fieldDefinition->fieldTypeIdentifier;
401
        if (is_array($value) || $this->complexFieldManager->managesField($fieldTypeIdentifier, $contentTypeIdentifier)) {
402
            return $this->complexFieldManager->getComplexFieldValue($fieldTypeIdentifier, $contentTypeIdentifier, $value, $context);
403
        }
404
405
        return $this->getSingleFieldValue($value, $fieldDefinition, $contentTypeIdentifier, $context);
406
    }
407
408
    /**
409
     * Create the field value for a primitive field
410
     * This function is needed to get past validation on Checkbox fieldtype (eZP bug)
411
     *
412
     * @param mixed $value
413
     * @param FieldDefinition $fieldDefinition
414
     * @param string $contentTypeIdentifier
415
     * @param array $context
416
     * @throws \InvalidArgumentException
417
     * @return mixed
418
     */
419
    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...
420
    {
421
        $fieldTypeIdentifier = $fieldDefinition->fieldTypeIdentifier;
422
        switch ($fieldTypeIdentifier) {
423
            case 'ezboolean':
424
                $value = new CheckboxValue(($value == 1) ? true : false);
425
                break;
426
            default:
427
                // do nothing
428
        }
429
430
        // q: do we really want this to happen by default on all scalar field values?
431
        // Note: if you want this *not* to happen, register a complex field for your scalar field...
432
        $value = $this->referenceResolver->resolveReference($value);
433
434
        return $value;
435
    }
436
437
    /**
438
     * Load user using either login, email, id - resolving eventual references
439
     * @param int|string $userKey
440
     * @return \eZ\Publish\API\Repository\Values\User\User
441
     */
442
    protected function getUser($userKey)
443
    {
444
        $userKey = $this->referenceResolver->resolveReference($userKey);
445
        return $this->userMatcher->matchOneByKey($userKey);
446
    }
447
448
    /**
449
     * Sets references to certain content attributes.
450
     * The Content Manager currently supports setting references to object_id and location_id
451
     *
452
     * @param \eZ\Publish\API\Repository\Values\Content\Content|ContentCollection $content
453
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute
454
     * @return boolean
455
     *
456
     * @todo add support for other attributes: remote ids, contentTypeId, contentTypeIdentifier, section, etc...
457
     */
458
    protected function setReferences($content)
459
    {
460
        if (!array_key_exists('references', $this->dsl)) {
461
            return false;
462
        }
463
464
        if ($content instanceof ContentCollection) {
465
            if (count($content) > 1) {
466
                throw new \InvalidArgumentException('Content Manager does not support setting references for creating/updating of multiple contents');
467
            }
468
            $content = reset($content);
469
        }
470
471
        foreach ($this->dsl['references'] as $reference) {
472
473
            switch ($reference['attribute']) {
474
                case 'object_id':
475
                case 'content_id':
476
                case 'id':
477
                    $value = $content->id;
478
                    break;
479
                case 'remote_id':
480
                case 'content_remote_id':
481
                    $value = $content->contentInfo->remoteId;
482
                    break;
483
                case 'location_id':
484
                    $value = $content->contentInfo->mainLocationId;
485
                    break;
486
                case 'path':
487
                    $locationService = $this->repository->getLocationService();
488
                    $value = $locationService->loadLocation($content->contentInfo->mainLocationId)->pathString;
489
                    break;
490
                default:
491
                    throw new \InvalidArgumentException('Content Manager does not support setting references for attribute ' . $reference['attribute']);
492
            }
493
494
            $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...
495
        }
496
497
        return true;
498
    }
499
500
    /**
501
     * @param int|string $date if integer, we assume a timestamp
502
     * @return \DateTime
503
     */
504
    protected function toDateTime($date)
505
    {
506
        if (is_int($date)) {
507
            return new \DateTime("@" . $date);
508
        } else {
509
            return new \DateTime($date);
510
        }
511
    }
512
513
    /**
514
     * @param string $matchType
515
     * @param string $matchValue
516
     * @param string $mode
517
     * @throws \Exception
518
     * @return array
519
     */
520
    public function generateMigration($matchType, $matchValue, $mode)
521
    {
522
        $this->loginUser(self::ADMIN_USER_ID);
523
        $contentCollection = $this->contentMatcher->match(array($matchType => $matchValue));
524
        $data = array();
525
526
        /** @var \eZ\Publish\API\Repository\Values\Content\Content $content */
527
        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...
528
            $location = $this->repository->getLocationService()->loadLocation($content->contentInfo->mainLocationId);
529
            $contentType = $this->repository->getContentTypeService()->loadContentType(
530
                $content->contentInfo->contentTypeId
531
            );
532
            $fieldTypeService = $this->repository->getFieldTypeService();
533
534
            $attributes = array();
535
            foreach ($content->getFieldsByLanguage($this->getLanguageCode()) as $field) {
536
                $fieldDefinition = $contentType->getFieldDefinition($field->fieldDefIdentifier);
537
                $fieldType = $fieldTypeService->getFieldType($fieldDefinition->fieldTypeIdentifier);
538
                $attributes[$field->fieldDefIdentifier] = $fieldType->toHash($field->value);
539
            }
540
541
            $contentData = array(
542
                'type' => 'content',
543
                'mode' => $mode
544
            );
545
546
            switch ($mode) {
547
                case 'create':
548
                    // @todo Add sort_field and sort_order
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
                    $contentData = array_merge(
563
                        $contentData,
564
                        array(
565
                            'match' => array(
566
                                'content_remote_id' => $content->contentInfo->remoteId
567
                            )
568
                        )
569
                    );
570
                    break;
571
                default:
572
                    throw new \Exception("Executor 'content' doesn't support mode '$mode'");
573
            }
574
575
            $contentData = array_merge(
576
                $contentData,
577
                array(
578
                    'lang' => $this->getLanguageCode(),
579
                    'section' => $content->contentInfo->sectionId,
580
                    'owner' => $content->contentInfo->ownerId,
581
                    'modification_date' => $content->contentInfo->modificationDate,
582
                    'publication_date' => $content->contentInfo->publishedDate,
583
                    'always_available' => $content->contentInfo->alwaysAvailable,
584
                    'attributes' => $attributes
585
                )
586
            );
587
            $data[] = $contentData;
588
        }
589
590
        return $data;
591
    }
592
}
593