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

ContentManager::create()   C

Complexity

Conditions 9
Paths 64

Size

Total Lines 52
Code Lines 31

Duplication

Lines 8
Ratio 15.38 %

Importance

Changes 9
Bugs 2 Features 1
Metric Value
cc 9
eloc 31
c 9
b 2
f 1
nc 64
nop 0
dl 8
loc 52
rs 6.5703

How to fix   Long Method   

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\ContentCreateStruct;
8
use eZ\Publish\API\Repository\Values\Content\ContentUpdateStruct;
9
use eZ\Publish\Core\FieldType\Checkbox\Value as CheckboxValue;
10
use Kaliop\eZMigrationBundle\API\Collection\ContentCollection;
11
use Kaliop\eZMigrationBundle\Core\Matcher\ContentMatcher;
12
use eZ\Publish\Core\Base\Exceptions\NotFoundException;
13
14
/**
15
 * Implements the actions for managing (create/update/delete) Content in the system through
16
 * migrations and abstracts away the eZ Publish Public API.
17
 *
18
 * @todo add support for updating of content metadata
19
 */
20
class ContentManager extends RepositoryExecutor
21
{
22
    protected $supportedStepTypes = array('content');
23
24
    protected $complexFieldManager;
25
    protected $contentMatcher;
26
27
    public function __construct(ContentMatcher $contentMatcher, $complexFieldManager)
28
    {
29
        $this->contentMatcher = $contentMatcher;
30
        $this->complexFieldManager = $complexFieldManager;
31
    }
32
33
    /**
34
     * Handle the content create migration action type
35
     */
36
    protected function create()
37
    {
38
        $contentService = $this->repository->getContentService();
39
        $locationService = $this->repository->getLocationService();
40
        $contentTypeService = $this->repository->getContentTypeService();
41
42
        $contentTypeIdentifier = $this->dsl['content_type'];
43
        if ($this->referenceResolver->isReference($contentTypeIdentifier)) {
44
            $contentTypeIdentifier = $this->referenceResolver->getReferenceValue($contentTypeIdentifier);
45
        }
46
        $contentType = $contentTypeService->loadContentTypeByIdentifier($contentTypeIdentifier);
47
48
        $contentCreateStruct = $contentService->newContentCreateStruct($contentType, $this->getLanguageCode());
49
        $this->setFields($contentCreateStruct, $this->dsl['attributes'], $contentType);
50
51
        if (array_key_exists('remote_id', $this->dsl)) {
52
            $contentCreateStruct->remoteId = $this->dsl['remote_id'];
53
        }
54
55
        // instantiate a location create struct from the parent location
56
        $locationId = $this->dsl['main_location'];
57
        if ($this->referenceResolver->isReference($locationId)) {
58
            $locationId = $this->referenceResolver->getReferenceValue($locationId);
59
        }
60
        $locationCreateStruct = $locationService->newLocationCreateStruct($locationId);
61
        if (array_key_exists('remote_id', $this->dsl)) {
62
            $locationCreateStruct->remoteId = $this->dsl['remote_id'] . '_location';
63
        }
64
65
        if (array_key_exists('priority', $this->dsl)) {
66
            $locationCreateStruct->priority = $this->dsl['priority'];
67
        }
68
69
        $locations = array($locationCreateStruct);
70
71
        if (array_key_exists('other_locations', $this->dsl)) {
72 View Code Duplication
            foreach ($this->dsl['other_locations'] as $otherLocation) {
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...
73
                $locationId = $otherLocation;
74
                if ($this->referenceResolver->isReference($locationId)) {
75
                    $locationId = $this->referenceResolver->getReferenceValue($otherLocation);
76
                }
77
                $secondaryLocationCreateStruct = $locationService->newLocationCreateStruct($locationId);
78
                array_push($locations, $secondaryLocationCreateStruct);
79
            }
80
        }
81
82
        // create a draft using the content and location create struct and publish it
83
        $draft = $contentService->createContent($contentCreateStruct, $locations);
0 ignored issues
show
Bug introduced by
It seems like $contentCreateStruct can also be of type object<eZ\Publish\API\Re...nt\ContentUpdateStruct>; however, eZ\Publish\API\Repositor...ervice::createContent() does only seem to accept object<eZ\Publish\API\Re...nt\ContentCreateStruct>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
84
        $content = $contentService->publishVersion($draft->versionInfo);
85
86
        $this->setReferences($content);
87
    }
88
89
    /**
90
     * Handle the content update migration action type
91
     *
92
     * @todo handle updating of more metadata fields
93
     */
94
    protected function update()
95
    {
96
        $contentService = $this->repository->getContentService();
97
        $contentTypeService = $this->repository->getContentTypeService();
98
99
        /*if (isset($this->dsl['object_id'])) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
52% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
100
            $objectId = $this->dsl['object_id'];
101
            if ($this->referenceResolver->isReference($objectId)) {
102
                $objectId = $this->referenceResolver->getReferenceValue($objectId);
103
            }
104
            $contentToUpdate = $contentService->loadContent($objectId);
105
            $contentInfo = $contentToUpdate->contentInfo;
106
        } else {
107
            $remoteId = $this->dsl['remote_id'];
108
            if ($this->referenceResolver->isReference($remoteId)) {
109
                $remoteId = $this->referenceResolver->getReferenceValue($remoteId);
110
            }
111
112
            //try {
113
                $contentInfo = $contentService->loadContentInfoByRemoteId($remoteId);
114
            // disabled in v2: we disallow this. For matching location-remote-id, use the 'match' keyword
115
            //} catch (\eZ\Publish\API\Repository\Exceptions\NotFoundException $e) {
116
            //    $location = $this->repository->getLocationService()->loadLocationByRemoteId($remoteId);
117
            //    $contentInfo = $location->contentInfo;
118
            //}
119
        }*/
120
121
        $contentCollection = $this->matchContents('update');
122
123
        if (count($contentCollection) > 1 && array_key_exists('references', $this->dsl)) {
124
            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");
125
        }
126
127
        $contentType = null;
128
129
        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...
130
            $contentInfo = $content->contentInfo;
131
132
            if ($contentType == null) {
133
                $contentType = $contentTypeService->loadContentType($contentInfo->contentTypeId);
134
            }
135
136
            $contentUpdateStruct = $contentService->newContentUpdateStruct();
137
138
            if (array_key_exists('attributes', $this->dsl)) {
139
                $this->setFields($contentUpdateStruct, $this->dsl['attributes'], $contentType);
140
            }
141
142
            $draft = $contentService->createContentDraft($contentInfo);
143
            $contentService->updateContent($draft->versionInfo,$contentUpdateStruct);
0 ignored issues
show
Bug introduced by
It seems like $contentUpdateStruct can also be of type object<eZ\Publish\API\Re...nt\ContentCreateStruct>; however, eZ\Publish\API\Repositor...ervice::updateContent() does only seem to accept object<eZ\Publish\API\Re...nt\ContentUpdateStruct>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
144
            $content = $contentService->publishVersion($draft->versionInfo);
145
146
            if (array_key_exists('new_remote_id', $this->dsl)) {
147
                // Update object remote ID
148
                $contentMetaDataUpdateStruct = $contentService->newContentMetadataUpdateStruct();
149
                $contentMetaDataUpdateStruct->remoteId = $this->dsl['new_remote_id'];
150
                $content = $contentService->updateContentMetadata($content->contentInfo, $contentMetaDataUpdateStruct);
151
152
                // Update main location remote ID
153
                // removed in v2: this is NOT generic!
154
                //$locationService = $this->repository->getLocationService();
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
155
                //$locationUpdateStruct = $locationService->newLocationUpdateStruct();
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
156
                //$locationUpdateStruct->remoteId = $this->dsl['new_remote_id'] . '_location';
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% 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...
157
                //$location = $locationService->loadLocation($content->contentInfo->mainLocationId);
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
158
                //$locationService->updateLocation($location, $locationUpdateStruct);
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% 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...
159
            }
160
161
            $this->setReferences($contentCollection);
0 ignored issues
show
Bug introduced by
It seems like $contentCollection defined by $this->matchContents('update') on line 121 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...
162
        }
163
    }
164
165
    /**
166
     * Handle the content delete migration action type
167
     */
168
    protected function delete()
169
    {
170
        $contentService = $this->repository->getContentService();
171
172
        $contentCollection = $this->matchContents('delete');
173
174
        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...
175
            try {
176
                $contentService->deleteContent($content->contentInfo);
177
            } catch (NotFoundException $e) {
178
                // Someone else (or even us, by virtue of location tree?) removed the content which we found just a
179
                // second ago. We can safely ignore this
180
            }
181
        }
182
    }
183
184
    /**
185
     * @param string $action
186
     * @return ContentCollection
187
     * @throws \Exception
188
     */
189 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...
190
    {
191
        if (!isset($this->dsl['object_id']) && !isset($this->dsl['remote_id']) && !isset($this->dsl['match'])) {
192
            throw new \Exception("The ID or remote ID of an object or a Match Condition is required to $action a new location.");
193
        }
194
195
        // Backwards compat
196
        if (!isset($this->dsl['match'])) {
197
            if (isset($this->dsl['object_id'])) {
198
                $this->dsl['match'] = array('content_id' => $this->dsl['object_id']);
199
            } elseif (isset($this->dsl['remote_id'])) {
200
                $this->dsl['match'] = array('content_remote_id' => $this->dsl['remote_id']);
201
            }
202
        }
203
204
        $match = $this->dsl['match'];
205
206
        // convert the references passed in the match
207
        foreach ($match as $condition => $values) {
208
            if (is_array($values)) {
209
                foreach ($values as $position => $value) {
210
                    if ($this->referenceResolver->isReference($value)) {
211
                        $match[$condition][$position] = $this->referenceResolver->getReferenceValue($value);
212
                    }
213
                }
214
            } else {
215
                if ($this->referenceResolver->isReference($values)) {
216
                    $match[$condition] = $this->referenceResolver->getReferenceValue($values);
217
                }
218
            }
219
        }
220
221
        return $this->contentMatcher->match($match);
222
    }
223
224
    /**
225
     * Helper function to set the fields of a ContentCreateStruct based on the DSL attribute settings.
226
     *
227
     * @param ContentCreateStruct|ContentUpdateStruct $createOrUpdateStruct
228
     * @param ContentType $contentType
229
     * @param array $fields
230
     */
231
    protected function setFields(&$createOrUpdateStruct, array $fields, ContentType $contentType)
232
    {
233
        foreach ($fields as $field) {
234
            // each $field is one key value pair
235
            // 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...
236
            $fieldIdentifier = key($field);
237
238
            $fieldType = $contentType->fieldDefinitionsByIdentifier[$fieldIdentifier];
0 ignored issues
show
Bug introduced by
The property fieldDefinitionsByIdentifier does not seem to exist. Did you mean fieldDefinitions?

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

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

Loading history...
239
240
            if (is_array($field[$fieldIdentifier])) {
241
                // Complex field might need special handling eg.: ezimage, ezbinaryfile
242
                $fieldValue = $this->getComplexFieldValue($field[$fieldIdentifier], $fieldType, $this->context);
243
            } else {
244
                // Primitive field eg.: ezstring, ezxml etc.
245
                $fieldValue = $this->getSingleFieldValue($field[$fieldIdentifier], $fieldType, $this->context);
246
            }
247
248
            $createOrUpdateStruct->setField($fieldIdentifier, $fieldValue, $this->getLanguageCode());
249
        }
250
    }
251
252
    /**
253
     * Create the field value for a primitive field
254
     * This function is needed to get past validation on Checkbox fieldtype (eZP bug)
255
     *
256
     * @param mixed $value
257
     * @param FieldDefinition $fieldDefinition
258
     * @param array $context
259
     * @throws \InvalidArgumentException
260
     * @return object
261
     */
262
    protected function getSingleFieldValue($value, FieldDefinition $fieldDefinition, array $context = array())
0 ignored issues
show
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...
263
    {
264
        switch ($fieldDefinition->fieldTypeIdentifier) {
265
            case 'ezboolean':
266
                $fieldValue = new CheckboxValue(($value == 1) ? true : false);
267
                break;
268
            default:
269
                $fieldValue = $value;
270
        }
271
272
        if ($this->referenceResolver->isReference($value)) {
273
            $fieldValue = $this->referenceResolver->getReferenceValue($value);
274
        }
275
276
        return $fieldValue;
277
    }
278
279
    /**
280
     * Create the field value for a complex field eg.: ezimage, ezfile
281
     *
282
     * @param FieldDefinition $fieldDefinition
283
     * @param array $fieldValueArray
284
     * @param array $context
285
     * @return object
286
     */
287
    protected function getComplexFieldValue(array $fieldValueArray, FieldDefinition $fieldDefinition, array $context = array())
288
    {
289
        return $this->complexFieldManager->getComplexFieldValue($fieldDefinition->fieldTypeIdentifier, $fieldValueArray, $context);
290
    }
291
292
    /**
293
     * Sets references to certain content attributes.
294
     * The Content Manager currently supports setting references to object_id and location_id
295
     *
296
     * @param \eZ\Publish\API\Repository\Values\Content\Content|ContentCollection $content
297
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute
298
     * @return boolean
299
     *
300
     * @todo add support for other attributes: remote ids, contentTypeId, contentTypeIdentifier, section, etc...
301
     */
302
    protected function setReferences($content)
303
    {
304
        if (!array_key_exists('references', $this->dsl)) {
305
            return false;
306
        }
307
308
        if ($content instanceof ContentCollection) {
309
            if (count($content) > 1) {
310
                throw new \InvalidArgumentException('Content Manager does not support setting references for creating/updating of multiple contents');
311
            }
312
            $content = reset($content);
313
        }
314
315
        foreach ($this->dsl['references'] as $reference) {
316
317
            switch ($reference['attribute']) {
318
                case 'object_id':
319
                case 'content_id':
320
                case 'id':
321
                    $value = $content->id;
322
                    break;
323
                case 'location_id':
324
                    $value = $content->contentInfo->mainLocationId;
325
                    break;
326
                case 'remote_id':
327
                case 'content_remote_id':
328
                    $value = $content->contentInfo->remoteId;
329
                    break;
330
331
                default:
332
                    throw new \InvalidArgumentException('Content Manager does not support setting references for attribute ' . $reference['attribute']);
333
            }
334
335
            $this->referenceResolver->addReference($reference['identifier'], $value);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Kaliop\eZMigrationBundle...erenceResolverInterface as the method addReference() does only exist in the following implementations of said interface: Kaliop\eZMigrationBundle...CustomReferenceResolver.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
336
        }
337
338
        return true;
339
    }
340
}
341