Completed
Push — master ( e72073...b2030e )
by Gaetano
08:10
created

ContentManager::getComplexFieldValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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