Completed
Push — master ( 9c56d3...0dd5d9 )
by Gaetano
07:08
created

ContentManager   F

Complexity

Total Complexity 66

Size/Duplication

Total Lines 371
Duplicated Lines 13.48 %

Coupling/Cohesion

Components 1
Dependencies 18

Test Coverage

Coverage 84.18%

Importance

Changes 0
Metric Value
wmc 66
lcom 1
cbo 18
dl 50
loc 371
ccs 133
cts 158
cp 0.8418
rs 2.9203
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
F create() 12 77 14
C update() 4 56 11
A delete() 0 17 3
C matchContents() 34 34 12
B setFields() 0 23 4
A setSection() 0 10 2
A getSingleFieldValue() 0 16 4
A getComplexFieldValue() 0 4 1
A getUser() 0 7 2
C setReferences() 0 41 12

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ContentManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ContentManager, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use eZ\Publish\API\Repository\Values\ContentType\ContentType;
6
use eZ\Publish\API\Repository\Values\ContentType\FieldDefinition;
7
use eZ\Publish\API\Repository\Values\Content\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 eZ\Publish\Core\Base\Exceptions\NotFoundException;
16
17
/**
18
 * Implements the actions for managing (create/update/delete) Content in the system through
19
 * migrations and abstracts away the eZ Publish Public API.
20
 *
21
 * @todo add support for updating of content metadata
22
 */
23
class ContentManager extends RepositoryExecutor
24
{
25
    protected $supportedStepTypes = array('content');
26
27 20
    protected $contentMatcher;
28
    protected $sectionMatcher;
29 20
    protected $userMatcher;
30 20
    protected $complexFieldManager;
31 20
    protected $locationManager;
32
33
    public function __construct(ContentMatcher $contentMatcher, SectionMatcher $sectionMatcher, UserMatcher $userMatcher, $complexFieldManager, $locationManager)
34
    {
35
        $this->contentMatcher = $contentMatcher;
36 4
        $this->sectionMatcher = $sectionMatcher;
37
        $this->userMatcher = $userMatcher;
38 4
        $this->complexFieldManager = $complexFieldManager;
39 4
        $this->locationManager = $locationManager;
40 4
    }
41
42 4
    /**
43 4
     * Handle the content create migration action type
44 3
     */
45 3
    protected function create()
46 4
    {
47
        $contentService = $this->repository->getContentService();
48 4
        $locationService = $this->repository->getLocationService();
49 4
        $contentTypeService = $this->repository->getContentTypeService();
50
51 4
        $contentTypeIdentifier = $this->dsl['content_type'];
52 1
        if ($this->referenceResolver->isReference($contentTypeIdentifier)) {
53 1
            $contentTypeIdentifier = $this->referenceResolver->getReferenceValue($contentTypeIdentifier);
54
        }
55
        $contentType = $contentTypeService->loadContentTypeByIdentifier($contentTypeIdentifier);
56 4
57 4
        $contentCreateStruct = $contentService->newContentCreateStruct($contentType, $this->getLanguageCode());
58 1
59 1
        $this->setFields($contentCreateStruct, $this->dsl['attributes'], $contentType);
60 4
61 4
        if (isset($this->dsl['remote_id'])) {
62 1
            $contentCreateStruct->remoteId = $this->dsl['remote_id'];
63 1
        }
64
65 4
        if (isset($this->dsl['section'])) {
66 1
            $sectionId = $this->dsl['section'];
67 1
            if ($this->referenceResolver->isReference($sectionId)) {
68
                $sectionId = $this->referenceResolver->getReferenceValue($sectionId);
69 4
            }
70
            $contentCreateStruct->sectionId = $sectionId;
71 4
        }
72
73 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...
74
            $owner = $this->getUser($this->dsl['owner']);
75
            $contentCreateStruct->ownerId = $owner->id;
76
        }
77
78
        // instantiate a location create struct from the parent location
79
        $locationId = $this->dsl['main_location'];
80
        if ($this->referenceResolver->isReference($locationId)) {
81
            $locationId = $this->referenceResolver->getReferenceValue($locationId);
82
        }
83 4
        $locationCreateStruct = $locationService->newLocationCreateStruct($locationId);
84 3
85
        if (isset($this->dsl['priority'])) {
86 3
            $locationCreateStruct->priority = $this->dsl['priority'];
87 3
        }
88
89
        if (isset($this->dsl['is_hidden'])) {
90
            $locationCreateStruct->hidden = $this->dsl['is_hidden'];
91
        }
92
93
        if (isset($this->dsl['sort_order'])) {
94 1
            $locationCreateStruct->sortOrder = $this->locationManager->getSortOrder($this->dsl['sort_order']);
95
        }
96 1
97 1
        if (isset($this->dsl['sort_field'])) {
98
            $locationCreateStruct->sortField = $this->locationManager->getSortField($this->dsl['sort_field']);
99
        }
100
101
        $locations = array($locationCreateStruct);
102
103
        if (isset($this->dsl['other_locations'])) {
104 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...
105
                $locationId = $otherLocation;
106
                if ($this->referenceResolver->isReference($locationId)) {
107
                    $locationId = $this->referenceResolver->getReferenceValue($otherLocation);
108
                }
109
                $secondaryLocationCreateStruct = $locationService->newLocationCreateStruct($locationId);
110
                array_push($locations, $secondaryLocationCreateStruct);
111
            }
112
        }
113
114
        // create a draft using the content and location create struct and publish it
115
        $draft = $contentService->createContent($contentCreateStruct, $locations);
116
        $content = $contentService->publishVersion($draft->versionInfo);
117
118
        $this->setReferences($content);
119
120
        return $content;
121 1
    }
122
123 1
    /**
124
     * Handle the content update migration action type
125
     *
126
     * @todo handle updating of more metadata fields
127 1
     */
128
    protected function update()
129 1
    {
130 1
        $contentService = $this->repository->getContentService();
131
        $contentTypeService = $this->repository->getContentTypeService();
132 1
133 1
        $contentCollection = $this->matchContents('update');
134 1
135
        if (count($contentCollection) > 1 && isset($this->dsl['references'])) {
136 1
            throw new \Exception("Can not execute Content update because multiple contents match, and a references section is specified in the dsl. References can be set when only 1 content matches");
137
        }
138 1
139 1
        $contentType = null;
140 1
141
        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...
142 1
            $contentInfo = $content->contentInfo;
143 1
144 1
            if ($contentType == null) {
145
                $contentType = $contentTypeService->loadContentType($contentInfo->contentTypeId);
146 1
            }
147
148
            $contentUpdateStruct = $contentService->newContentUpdateStruct();
149
150
            if (isset($this->dsl['attributes'])) {
151
                $this->setFields($contentUpdateStruct, $this->dsl['attributes'], $contentType);
152
            }
153
154
            $draft = $contentService->createContentDraft($contentInfo);
155
            $contentService->updateContent($draft->versionInfo,$contentUpdateStruct);
156
            $content = $contentService->publishVersion($draft->versionInfo);
157
158
            if (isset($this->dsl['new_remote_id']) || isset($this->dsl['new_remote_id'])) {
159
                $contentMetaDataUpdateStruct = $contentService->newContentMetadataUpdateStruct();
160
161 1
                if (isset($this->dsl['new_remote_id'])) {
162 1
                    $contentMetaDataUpdateStruct->remoteId = $this->dsl['new_remote_id'];
163 1
                }
164
165 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...
166
                    $owner = $this->getUser($this->dsl['owner']);
167
                    $contentMetaDataUpdateStruct->ownerId = $owner->id;
168 3
                }
169
170 3
                $content = $contentService->updateContentMetadata($content->contentInfo, $contentMetaDataUpdateStruct);
171
            }
172 3
173
            if (isset($this->dsl['section'])) {
174 3
                $this->setSection($content, $this->dsl['section']);
175
            }
176 3
177 3
            $contentCollection[$key] = $content;
178
        }
179
180
        $this->setReferences($contentCollection);
0 ignored issues
show
Bug introduced by
It seems like $contentCollection defined by $this->matchContents('update') on line 133 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...
181 3
182 3
        return $contentCollection;
183
    }
184
185
    /**
186
     * Handle the content delete migration action type
187
     */
188
    protected function delete()
189 3
    {
190
        $contentService = $this->repository->getContentService();
191 3
192
        $contentCollection = $this->matchContents('delete');
193
194
        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...
195
            try {
196 3
                $contentService->deleteContent($content->contentInfo);
197 1
            } catch (NotFoundException $e) {
198 1
                // Someone else (or even us, by virtue of location tree?) removed the content which we found just a
199 1
                // second ago. We can safely ignore this
200
            }
201
        }
202 1
203
        return $contentCollection;
204 3
    }
205
206
    /**
207 3
     * @param string $action
208 3
     * @return ContentCollection
209 1
     * @throws \Exception
210 1
     */
211 1 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...
212 1
    {
213 1
        if (!isset($this->dsl['object_id']) && !isset($this->dsl['remote_id']) && !isset($this->dsl['match'])) {
214 1
            throw new \Exception("The ID or remote ID of an object or a Match Condition is required to $action a new location.");
215 3
        }
216 3
217 3
        // Backwards compat
218
        if (!isset($this->dsl['match'])) {
219 3
            if (isset($this->dsl['object_id'])) {
220
                $this->dsl['match'] = array('content_id' => $this->dsl['object_id']);
221 3
            } elseif (isset($this->dsl['remote_id'])) {
222
                $this->dsl['match'] = array('content_remote_id' => $this->dsl['remote_id']);
223
            }
224
        }
225
226
        $match = $this->dsl['match'];
227
228
        // convert the references passed in the match
229
        foreach ($match as $condition => $values) {
230
            if (is_array($values)) {
231 4
                foreach ($values as $position => $value) {
232
                    if ($this->referenceResolver->isReference($value)) {
233 4
                        $match[$condition][$position] = $this->referenceResolver->getReferenceValue($value);
234
                    }
235
                }
236 4
            } else {
237
                if ($this->referenceResolver->isReference($values)) {
238 4
                    $match[$condition] = $this->referenceResolver->getReferenceValue($values);
239
                }
240 4
            }
241
        }
242 1
243 1
        return $this->contentMatcher->match($match);
244
    }
245 4
246 3
    /**
247
     * Helper function to set the fields of a ContentCreateStruct based on the DSL attribute settings.
248 4
     *
249 4
     * @param ContentCreateStruct|ContentUpdateStruct $createOrUpdateStruct
250 4
     * @param ContentType $contentType
251
     * @param array $fields
252
     * @throws \Exception
253
     */
254
    protected function setFields($createOrUpdateStruct, array $fields, ContentType $contentType)
255
    {
256
        foreach ($fields as $field) {
257
            // each $field is one key value pair
258
            // 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...
259
            $fieldIdentifier = key($field);
260
261
            $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...
262 4
            if ($fieldType == null) {
263
                throw new \Exception("Field '$fieldIdentifier' is not present in field type '{$contentType->identifier}'");
264 4
            }
265 4
266
            if (is_array($field[$fieldIdentifier])) {
267
                // Complex field might need special handling eg.: ezimage, ezbinaryfile
268 4
                $fieldValue = $this->getComplexFieldValue($field[$fieldIdentifier], $fieldType, $this->context);
269 4
            } else {
270 4
                // Primitive field eg.: ezstring, ezxml etc.
271
                $fieldValue = $this->getSingleFieldValue($field[$fieldIdentifier], $fieldType, $this->context);
272 4
            }
273 1
274 1
            $createOrUpdateStruct->setField($fieldIdentifier, $fieldValue, $this->getLanguageCode());
275
        }
276 4
    }
277
278
    protected function setSection(Content $content, $sectionId)
279
    {
280
        if ($this->referenceResolver->isReference($sectionId)) {
281
            $sectionId = $this->referenceResolver->getReferenceValue($sectionId);
282
        }
283
        $section = $this->sectionMatcher->matchByKey($sectionId);
284
285
        $sectionService = $this->repository->getSectionService();
286
        $sectionService->assignSection($content->contentInfo, $section);
287 1
    }
288
289 1
    /**
290 1
     * Create the field value for a primitive field
291
     * This function is needed to get past validation on Checkbox fieldtype (eZP bug)
292
     *
293
     * @param mixed $value
294
     * @param FieldDefinition $fieldDefinition
295
     * @param array $context
296
     * @throws \InvalidArgumentException
297
     * @return object
298
     */
299
    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...
300
    {
301
        switch ($fieldDefinition->fieldTypeIdentifier) {
302 3
            case 'ezboolean':
303
                $fieldValue = new CheckboxValue(($value == 1) ? true : false);
304 3
                break;
305 2
            default:
306
                $fieldValue = $value;
307
        }
308 3
309
        if ($this->referenceResolver->isReference($value)) {
310
            $fieldValue = $this->referenceResolver->getReferenceValue($value);
311
        }
312
313
        return $fieldValue;
314
    }
315 3
316
    /**
317 3
     * Create the field value for a complex field eg.: ezimage, ezfile
318 3
     *
319 3
     * @param FieldDefinition $fieldDefinition
320 3
     * @param array $fieldValueArray
321 3
     * @param array $context
322 3
     * @return object
323 2
     */
324 2
    protected function getComplexFieldValue(array $fieldValueArray, FieldDefinition $fieldDefinition, array $context = array())
325 2
    {
326 1
        return $this->complexFieldManager->getComplexFieldValue($fieldDefinition->fieldTypeIdentifier, $fieldValueArray, $context);
327 1
    }
328 1
329 1
    /**
330
     * Load user using either login, email, id - resolving eventual references
331
     * @param int|string $key
332
     * @return \eZ\Publish\API\Repository\Values\User\User
333 3
     */
334
    protected function getUser($key)
335 3
    {
336 3
        if ($this->referenceResolver->isReference($key)) {
337
            $key = $this->referenceResolver->getReferenceValue($key);
338 3
        }
339
        return $this->userMatcher->matchByKey($key);
340
    }
341
342
    /**
343
     * Sets references to certain content attributes.
344
     * The Content Manager currently supports setting references to object_id and location_id
345
     *
346
     * @param \eZ\Publish\API\Repository\Values\Content\Content|ContentCollection $content
347
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute
348
     * @return boolean
349
     *
350
     * @todo add support for other attributes: remote ids, contentTypeId, contentTypeIdentifier, section, etc...
351
     */
352
    protected function setReferences($content)
353
    {
354
        if (!array_key_exists('references', $this->dsl)) {
355
            return false;
356
        }
357
358
        if ($content instanceof ContentCollection) {
359
            if (count($content) > 1) {
360
                throw new \InvalidArgumentException('Content Manager does not support setting references for creating/updating of multiple contents');
361
            }
362
            $content = reset($content);
363
        }
364
365
        foreach ($this->dsl['references'] as $reference) {
366
367
            switch ($reference['attribute']) {
368
                case 'object_id':
369
                case 'content_id':
370
                case 'id':
371
                    $value = $content->id;
372
                    break;
373
                case 'remote_id':
374
                case 'content_remote_id':
375
                    $value = $content->contentInfo->remoteId;
376
                    break;
377
                case 'location_id':
378
                    $value = $content->contentInfo->mainLocationId;
379
                    break;
380
                case 'path':
381
                    $locationService = $this->repository->getLocationService();
382
                    $value = $locationService->loadLocation($content->contentInfo->mainLocationId)->pathString;
383
                    break;
384
                default:
385
                    throw new \InvalidArgumentException('Content Manager does not support setting references for attribute ' . $reference['attribute']);
386
            }
387
388
            $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...
389
        }
390
391
        return true;
392
    }
393
}
394