Completed
Push — master ( 756c4d...b4efa6 )
by Gaetano
11:39 queued 01:45
created

ContentManager::setObjectStates()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 0
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 2
crap 6
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\Core\Matcher\ContentMatcher;
13
use Kaliop\eZMigrationBundle\Core\Matcher\SectionMatcher;
14
use Kaliop\eZMigrationBundle\Core\Matcher\UserMatcher;
15
use Kaliop\eZMigrationBundle\Core\Matcher\ObjectStateMatcher;
16
use eZ\Publish\Core\Base\Exceptions\NotFoundException;
17
18
/**
19
 * Implements the actions for managing (create/update/delete) Content in the system through
20
 * migrations and abstracts away the eZ Publish Public API.
21
 *
22
 * @todo add support for updating of content metadata
23
 */
24
class ContentManager extends RepositoryExecutor
25
{
26
    protected $supportedStepTypes = array('content');
27 20
28
    protected $contentMatcher;
29 20
    protected $sectionMatcher;
30 20
    protected $userMatcher;
31 20
    protected $objectStateMatcher;
32
    protected $complexFieldManager;
33
    protected $locationManager;
34
35
    public function __construct(ContentMatcher $contentMatcher, SectionMatcher $sectionMatcher, UserMatcher $userMatcher,
36 4
        ObjectStateMatcher $objectStateMatcher, $complexFieldManager, $locationManager)
37
    {
38 4
        $this->contentMatcher = $contentMatcher;
39 4
        $this->sectionMatcher = $sectionMatcher;
40 4
        $this->userMatcher = $userMatcher;
41
        $this->objectStateMatcher = $objectStateMatcher;
42 4
        $this->complexFieldManager = $complexFieldManager;
43 4
        $this->locationManager = $locationManager;
44 3
    }
45 3
46 4
    /**
47
     * Handle the content create migration action type
48 4
     */
49 4
    protected function create()
50
    {
51 4
        $contentService = $this->repository->getContentService();
52 1
        $locationService = $this->repository->getLocationService();
53 1
        $contentTypeService = $this->repository->getContentTypeService();
54
55
        $contentTypeIdentifier = $this->dsl['content_type'];
56 4
        $contentTypeIdentifier = $this->referenceResolver->resolveReference($contentTypeIdentifier);
57 4
        /// @todo use a contenttypematcher
58 1
        $contentType = $contentTypeService->loadContentTypeByIdentifier($contentTypeIdentifier);
59 1
60 4
        $contentCreateStruct = $contentService->newContentCreateStruct($contentType, $this->getLanguageCode());
61 4
62 1
        $this->setFields($contentCreateStruct, $this->dsl['attributes'], $contentType);
63 1
64
        if (isset($this->dsl['always_available'])) {
65 4
            $contentCreateStruct->alwaysAvailable = $this->dsl['always_available'];
66 1
        } else {
67 1
            // Can be removed when https://github.com/kaliop-uk/ezmigrationbundle/pull/88 is merged
68
            $contentCreateStruct->alwaysAvailable = $contentType->defaultAlwaysAvailable;
69 4
        }
70
71 4
        if (isset($this->dsl['remote_id'])) {
72
            $contentCreateStruct->remoteId = $this->dsl['remote_id'];
73
        }
74
75
        if (isset($this->dsl['section'])) {
76
            $sectionId = $this->dsl['section'];
77
            $sectionId = $this->referenceResolver->resolveReference($sectionId);
78
            $contentCreateStruct->sectionId = $sectionId;
79
        }
80
81 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...
82
            $owner = $this->getUser($this->dsl['owner']);
83 4
            $contentCreateStruct->ownerId = $owner->id;
84 3
        }
85
86 3
        // This is a bit tricky, as the eZPublish API does not support having a different creator and owner with only 1 version.
87 3
        // We allow it, hoping that nothing gets broken because of it
88
        if (isset($this->dsl['version_creator'])) {
89
            $realContentOwnerId = $contentCreateStruct->ownerId;
90
            if ($realContentOwnerId == null) {
91
                $realContentOwnerId = $this->repository->getCurrentUser()->id;
92
            }
93
            $versionCreator = $this->getUser($this->dsl['version_creator']);
94 1
            $contentCreateStruct->ownerId = $versionCreator->id;
95
        }
96 1
97 1
        if (isset($this->dsl['modification_date'])) {
98
            $contentCreateStruct->modificationDate = $this->toDateTime($this->dsl['modification_date']);
99
        }
100
101
        // instantiate a location create struct from the parent location:
102
        // BC
103
        $locationId = isset($this->dsl['parent_location']) ? $this->dsl['parent_location'] : (
104
            isset($this->dsl['main_location']) ? $this->dsl['main_location'] : null
105
        );
106
        // 1st resolve references
107
        $locationId = $this->referenceResolver->resolveReference($locationId);
108
        // 2nd allow to specify the location via remote_id
109
        $locationId = $this->locationManager->matchLocationByKey($locationId)->id;
110
        $locationCreateStruct = $locationService->newLocationCreateStruct($locationId);
111
112
        if (isset($this->dsl['location_remote_id'])) {
113
            $locationCreateStruct->remoteId = $this->dsl['location_remote_id'];
114
        }
115
116
        if (isset($this->dsl['priority'])) {
117
            $locationCreateStruct->priority = $this->dsl['priority'];
118
        }
119
120
        if (isset($this->dsl['is_hidden'])) {
121 1
            $locationCreateStruct->hidden = $this->dsl['is_hidden'];
122
        }
123 1
124
        if (isset($this->dsl['sort_field'])) {
125
            $locationCreateStruct->sortField = $this->locationManager->getSortField($this->dsl['sort_field']);
126
        } else {
127 1
            $locationCreateStruct->sortField = $contentType->defaultSortField;
128
        }
129 1
130 1
        if (isset($this->dsl['sort_order'])) {
131
            $locationCreateStruct->sortOrder = $this->locationManager->getSortOrder($this->dsl['sort_order']);
132 1
        } else {
133 1
            $locationCreateStruct->sortOrder = $contentType->defaultSortOrder;
134 1
        }
135
136 1
        $locations = array($locationCreateStruct);
137
138 1
        // BC
139 1
        $other_locations = isset($this->dsl['other_parent_locations']) ? $this->dsl['other_parent_locations'] : (
140 1
            isset($this->dsl['other_locations']) ? $this->dsl['other_locations'] : null
141
        );
142 1
        if (isset($other_locations)) {
143 1
            foreach ($other_locations as $locationId) {
144 1
                $locationId = $this->referenceResolver->resolveReference($locationId);
145
                $locationId = $this->locationManager->matchLocationByKey($locationId)->id;
146 1
                $secondaryLocationCreateStruct = $locationService->newLocationCreateStruct($locationId);
147
                array_push($locations, $secondaryLocationCreateStruct);
148
            }
149
        }
150
151
        // create a draft using the content and location create struct and publish it
152
        $draft = $contentService->createContent($contentCreateStruct, $locations);
153
        $content = $contentService->publishVersion($draft->versionInfo);
154
155
        if (isset($this->dsl['object_states'])) {
156
            $this->setObjectStates($content, $this->dsl['object_states']);
157
        }
158
159
        // 2nd part of the hack: re-set the content owner to its intended value
160
        if (isset($this->dsl['version_creator']) || isset($this->dsl['publication_date'])) {
161 1
            $contentMetaDataUpdateStruct = $contentService->newContentMetadataUpdateStruct();
162 1
163 1
            if (isset($this->dsl['version_creator'])) {
164
                $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...
165
            }
166
            if (isset($this->dsl['publication_date'])) {
167
                $contentMetaDataUpdateStruct->publishedDate = $this->toDateTime($this->dsl['publication_date']);
168 3
            }
169
170 3
            $contentService->updateContentMetadata($content->contentInfo, $contentMetaDataUpdateStruct);
171
        }
172 3
173
        $this->setReferences($content);
174 3
175
        return $content;
176 3
    }
177 3
178
    /**
179
     * Handle the content update migration action type
180
     *
181 3
     * @todo handle updating of more metadata fields
182 3
     */
183
    protected function update()
184
    {
185
        $contentService = $this->repository->getContentService();
186
        $contentTypeService = $this->repository->getContentTypeService();
187
188
        $contentCollection = $this->matchContents('update');
189 3
190
        if (count($contentCollection) > 1 && isset($this->dsl['references'])) {
191 3
            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");
192
        }
193
194
        $contentType = null;
195
196 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...
197 1
            $contentInfo = $content->contentInfo;
198 1
199 1
            if ($contentType == null) {
200
                $contentType = $contentTypeService->loadContentType($contentInfo->contentTypeId);
201
            }
202 1
203
            $contentUpdateStruct = $contentService->newContentUpdateStruct();
204 3
205
            if (isset($this->dsl['attributes'])) {
206
                $this->setFields($contentUpdateStruct, $this->dsl['attributes'], $contentType);
207 3
            }
208 3
209 1
            $versionCreator = null;
210 1
            if (isset($this->dsl['version_creator'])) {
211 1
                $versionCreator = $this->getUser($this->dsl['version_creator']);
212 1
            }
213 1
214 1
            $draft = $contentService->createContentDraft($contentInfo, null, $versionCreator);
215 3
            $contentService->updateContent($draft->versionInfo, $contentUpdateStruct);
216 3
            $content = $contentService->publishVersion($draft->versionInfo);
217 3
218
            if (isset($this->dsl['new_remote_id']) || isset($this->dsl['new_remote_id']) ||
219 3
                isset($this->dsl['modification_date']) || isset($this->dsl['publication_date'])) {
220
221 3
                $contentMetaDataUpdateStruct = $contentService->newContentMetadataUpdateStruct();
222
223
                if (isset($this->dsl['new_remote_id'])) {
224
                    $contentMetaDataUpdateStruct->remoteId = $this->dsl['new_remote_id'];
225
                }
226
227 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...
228
                    $owner = $this->getUser($this->dsl['owner']);
229
                    $contentMetaDataUpdateStruct->ownerId = $owner->id;
230
                }
231 4
232
                if (isset($this->dsl['modification_date'])) {
233 4
                    $contentMetaDataUpdateStruct->modificationDate = $this->toDateTime($this->dsl['modification_date']);
234
                }
235
236 4
                if (isset($this->dsl['publication_date'])) {
237
                    $contentMetaDataUpdateStruct->publishedDate = $this->toDateTime($this->dsl['publication_date']);
238 4
                }
239
240 4
                $content = $contentService->updateContentMetadata($content->contentInfo, $contentMetaDataUpdateStruct);
241
            }
242 1
243 1
            if (isset($this->dsl['section'])) {
244
                $this->setSection($content, $this->dsl['section']);
245 4
            }
246 3
247
            if (isset($this->dsl['object_states'])) {
248 4
                $this->setObjectStates($content, $this->dsl['object_states']);
249 4
            }
250 4
251
            $contentCollection[$key] = $content;
252
        }
253
254
        $this->setReferences($contentCollection);
0 ignored issues
show
Bug introduced by
It seems like $contentCollection defined by $this->matchContents('update') on line 188 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...
255
256
        return $contentCollection;
257
    }
258
259
    /**
260
     * Handle the content delete migration action type
261
     */
262 4
    protected function delete()
263
    {
264 4
        $contentService = $this->repository->getContentService();
265 4
266
        $contentCollection = $this->matchContents('delete');
267
268 4
        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...
269 4
            try {
270 4
                $contentService->deleteContent($content->contentInfo);
271
            } catch (NotFoundException $e) {
272 4
                // Someone else (or even us, by virtue of location tree?) removed the content which we found just a
273 1
                // second ago. We can safely ignore this
274 1
            }
275
        }
276 4
277
        return $contentCollection;
278
    }
279
280
    /**
281
     * @param string $action
282
     * @return ContentCollection
283
     * @throws \Exception
284
     */
285 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...
286
    {
287 1
        if (!isset($this->dsl['object_id']) && !isset($this->dsl['remote_id']) && !isset($this->dsl['match'])) {
288
            throw new \Exception("The ID or remote ID of an object or a Match Condition is required to $action a new location.");
289 1
        }
290 1
291
        // Backwards compat
292
        if (!isset($this->dsl['match'])) {
293
            if (isset($this->dsl['object_id'])) {
294
                $this->dsl['match'] = array('content_id' => $this->dsl['object_id']);
295
            } elseif (isset($this->dsl['remote_id'])) {
296
                $this->dsl['match'] = array('content_remote_id' => $this->dsl['remote_id']);
297
            }
298
        }
299
300
        $match = $this->dsl['match'];
301
302 3
        // convert the references passed in the match
303
        foreach ($match as $condition => $values) {
304 3
            if (is_array($values)) {
305 2
                foreach ($values as $position => $value) {
306
                    $match[$condition][$position] = $this->referenceResolver->resolveReference($value);
307
                }
308 3
            } else {
309
                $match[$condition] = $this->referenceResolver->resolveReference($values);
310
            }
311
        }
312
313
        return $this->contentMatcher->match($match);
314
    }
315 3
316
    /**
317 3
     * Helper function to set the fields of a ContentCreateStruct based on the DSL attribute settings.
318 3
     *
319 3
     * @param ContentCreateStruct|ContentUpdateStruct $createOrUpdateStruct
320 3
     * @param ContentType $contentType
321 3
     * @param array $fields see description of expected format in code below
322 3
     * @throws \Exception
323 2
     */
324 2
    protected function setFields($createOrUpdateStruct, array $fields, ContentType $contentType)
325 2
    {
326 1
        $i = 0;
327 1
        // the 'easy' yml: key = field name, value = value
328 1
        // deprecated: the 'legacy' yml: key = numerical index, value = array ( field name => value )
329 1
        foreach ($fields as $key => $field) {
330
331
            if ($key === $i && is_array($field) && count($field) == 1) {
332
                // each $field is one key value pair
333 3
                // 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...
334
                reset($field);
335 3
                $fieldIdentifier = key($field);
336 3
                $fieldValue = $field[$fieldIdentifier];
337
            } else {
338 3
                $fieldIdentifier = $key;
339
                $fieldValue = $field;
340
            }
341
342
            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...
343
                throw new \Exception("Field '$fieldIdentifier' is not present in field type '{$contentType->identifier}'");
344
            }
345
346
            $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...
347
            $fieldValue = $this->getFieldValue($fieldValue, $fieldDefinition, $contentType->identifier, $this->context);
348
349
            $createOrUpdateStruct->setField($fieldIdentifier, $fieldValue, $this->getLanguageCode());
350
351
            $i++;
352
        }
353
    }
354
355
    protected function setSection(Content $content, $sectionKey)
356
    {
357
        $sectionKey = $this->referenceResolver->resolveReference($sectionKey);
358
        $section = $this->sectionMatcher->matchOneByKey($sectionKey);
359
360
        $sectionService = $this->repository->getSectionService();
361
        $sectionService->assignSection($content->contentInfo, $section);
362
    }
363
364
    protected function setObjectStates(Content $content, array $stateKeys)
365
    {
366
        foreach ($stateKeys as $stateKey) {
367
            $stateKey = $this->referenceResolver->resolveReference($stateKey);
368
            /** @var \eZ\Publish\API\Repository\Values\ObjectState\ObjectState $state */
369
            $state = $this->objectStateMatcher->matchOneByKey($stateKey);
370
371
            $stateService = $this->repository->getObjectStateService();
372
            $stateService->setContentState($content->contentInfo, $state->getObjectStateGroup(), $state);
373
        }
374
    }
375
376
    /**
377
     * Create the field value for either a primitive (ie. scalar) or complex field
378
     *
379
     * @param mixed $value
380
     * @param FieldDefinition $fieldDefinition
381
     * @param string $contentTypeIdentifier
382
     * @param array $context
383
     * @throws \InvalidArgumentException
384
     * @return mixed
385
     */
386
    protected function getFieldValue($value, FieldDefinition $fieldDefinition, $contentTypeIdentifier, array $context = array())
387
    {
388
        $fieldTypeIdentifier = $fieldDefinition->fieldTypeIdentifier;
389
        if (is_array($value) || $this->complexFieldManager->managesField($fieldTypeIdentifier, $contentTypeIdentifier)) {
390
            return $this->complexFieldManager->getComplexFieldValue($fieldTypeIdentifier, $contentTypeIdentifier, $value, $context);
391
        }
392
393
        return $this->getSingleFieldValue($value, $fieldDefinition, $contentTypeIdentifier, $context);
394
    }
395
396
    /**
397
     * Create the field value for a primitive field
398
     * This function is needed to get past validation on Checkbox fieldtype (eZP bug)
399
     *
400
     * @param mixed $value
401
     * @param FieldDefinition $fieldDefinition
402
     * @param string $contentTypeIdentifier
403
     * @param array $context
404
     * @throws \InvalidArgumentException
405
     * @return mixed
406
     */
407
    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...
408
    {
409
        $fieldTypeIdentifier = $fieldDefinition->fieldTypeIdentifier;
410
        switch ($fieldTypeIdentifier) {
411
            case 'ezboolean':
412
                $value = new CheckboxValue(($value == 1) ? true : false);
413
                break;
414
            default:
415
                // do nothing
416
        }
417
418
        // q: do we really want this to happen by default on all scalar field values?
419
        // Note: if you want this *not* to happen, register a complex field for your scalar field...
420
        $value = $this->referenceResolver->resolveReference($value);
421
422
        return $value;
423
    }
424
425
    /**
426
     * Load user using either login, email, id - resolving eventual references
427
     * @param int|string $userKey
428
     * @return \eZ\Publish\API\Repository\Values\User\User
429
     */
430
    protected function getUser($userKey)
431
    {
432
        $userKey = $this->referenceResolver->resolveReference($userKey);
433
        return $this->userMatcher->matchOneByKey($userKey);
434
    }
435
436
    /**
437
     * Sets references to certain content attributes.
438
     * The Content Manager currently supports setting references to object_id and location_id
439
     *
440
     * @param \eZ\Publish\API\Repository\Values\Content\Content|ContentCollection $content
441
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute
442
     * @return boolean
443
     *
444
     * @todo add support for other attributes: remote ids, contentTypeId, contentTypeIdentifier, section, etc...
445
     */
446
    protected function setReferences($content)
447
    {
448
        if (!array_key_exists('references', $this->dsl)) {
449
            return false;
450
        }
451
452
        if ($content instanceof ContentCollection) {
453
            if (count($content) > 1) {
454
                throw new \InvalidArgumentException('Content Manager does not support setting references for creating/updating of multiple contents');
455
            }
456
            $content = reset($content);
457
        }
458
459
        foreach ($this->dsl['references'] as $reference) {
460
461
            switch ($reference['attribute']) {
462
                case 'object_id':
463
                case 'content_id':
464
                case 'id':
465
                    $value = $content->id;
466
                    break;
467
                case 'remote_id':
468
                case 'content_remote_id':
469
                    $value = $content->contentInfo->remoteId;
470
                    break;
471
                case 'location_id':
472
                    $value = $content->contentInfo->mainLocationId;
473
                    break;
474
                case 'path':
475
                    $locationService = $this->repository->getLocationService();
476
                    $value = $locationService->loadLocation($content->contentInfo->mainLocationId)->pathString;
477
                    break;
478
                default:
479
                    throw new \InvalidArgumentException('Content Manager does not support setting references for attribute ' . $reference['attribute']);
480
            }
481
482
            $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...
483
        }
484
485
        return true;
486
    }
487
488
    /**
489
     * @param int|string $date if integer, we assume a timestamp
490
     * @return \DateTime
491
     */
492
    protected function toDateTime($date)
493
    {
494
        if (is_int($date)) {
495
            return new \DateTime("@" . $date);
496
        } else {
497
            return new \DateTime($date);
498
        }
499
    }
500
}
501