Completed
Push — master ( e7f7b5...2ae0e9 )
by Gaetano
06:53
created

ContentManager::getComplexFieldValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 3
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use eZ\Publish\API\Repository\FieldType;
6
use eZ\Publish\API\Repository\Values\ContentType\ContentType;
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
11
/**
12
 * Implements the actions for managing (create/update/delete) Content in the system through
13
 * migrations and abstracts away the eZ Publish Public API.
14
 *
15
 * @todo add support for updating of content metadata
16
 */
17
class ContentManager extends RepositoryExecutor
18
{
19
    protected $supportedStepTypes = array('content');
20
21
    protected $complexFieldManager;
22
23
    public function __construct($complexFieldManager)
24
    {
25
        $this->complexFieldManager = $complexFieldManager;
26
    }
27
28
    /**
29
     * @param string $action
30
     * @return ContentCollection
31
     * @throws \Exception
32
     */
33 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...
34
    {
35
        if (!isset($this->dsl['object_id']) && !isset($this->dsl['remote_id']) && !isset($this->dsl['match'])) {
36
            throw new \Exception("The ID or remote ID of an object or a Match Condition is required to $action a new location.");
37
        }
38
39
        // Backwards compat
40
        if (!isset($this->dsl['match'])) {
41
            if (isset($this->dsl['object_id'])) {
42
                $this->dsl['match'] = array('content_id' => $this->dsl['object_id']);
43
            } elseif (isset($this->dsl['remote_id'])) {
44
                $this->dsl['match'] = array('content_remote_id' => $this->dsl['remote_id']);
45
            }
46
        }
47
48
        $match = $this->dsl['match'];
49
50
        // convert the references passed in the match
51
        foreach ($match as $condition => $values) {
52
            if (is_array($values)) {
53
                foreach ($values as $position => $value) {
54
                    if ($this->referenceResolver->isReference($value)) {
55
                        $match[$condition][$position] = $this->referenceResolver->getReferenceValue($value);
56
                    }
57
                }
58
            } else {
59
                if ($this->referenceResolver->isReference($values)) {
60
                    $match[$condition] = $this->referenceResolver->getReferenceValue($values);
61
                }
62
            }
63
        }
64
65
        return $this->contentMatcher->matchContent($match);
0 ignored issues
show
Bug introduced by
The property contentMatcher does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
66
    }
67
68
    /**
69
     * Handle the content create migration action type
70
     */
71
    protected function create()
72
    {
73
        $this->loginUser();
74
75
        $contentService = $this->repository->getContentService();
76
        $locationService = $this->repository->getLocationService();
77
        $contentTypeService = $this->repository->getContentTypeService();
78
79
        $contentTypeIdentifier = $this->dsl['content_type'];
80
        if ($this->referenceResolver->isReference($contentTypeIdentifier)) {
81
            $contentTypeIdentifier = $this->referenceResolver->getReferenceValue($contentTypeIdentifier);
82
        }
83
        $contentType = $contentTypeService->loadContentTypeByIdentifier($contentTypeIdentifier);
84
85
        // FIXME: Defaulting in language code for now
86
        $contentCreateStruct = $contentService->newContentCreateStruct($contentType, self::DEFAULT_LANGUAGE_CODE);
87
        $this->setFields($contentCreateStruct, $this->dsl['attributes'], $contentType);
88
89
        if (array_key_exists('remote_id', $this->dsl)) {
90
            $contentCreateStruct->remoteId = $this->dsl['remote_id'];
91
        }
92
93
        // instantiate a location create struct from the parent location
94
        $locationId = $this->dsl['main_location'];
95
        if ($this->referenceResolver->isReference($locationId)) {
96
            $locationId = $this->referenceResolver->getReferenceValue($locationId);
97
        }
98
        $locationCreateStruct = $locationService->newLocationCreateStruct($locationId);
99
        if (array_key_exists('remote_id', $this->dsl)) {
100
            $locationCreateStruct->remoteId = $this->dsl['remote_id'] . '_location';
101
        }
102
103
        if (array_key_exists('priority', $this->dsl)) {
104
            $locationCreateStruct->priority = $this->dsl['priority'];
105
        }
106
107
        $locations = array($locationCreateStruct);
108
109
        if (array_key_exists('other_locations', $this->dsl)) {
110 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...
111
                $locationId = $otherLocation;
112
                if ($this->referenceResolver->isReference($locationId)) {
113
                    $locationId = $this->referenceResolver->getReferenceValue($otherLocation);
114
                }
115
                $secondaryLocationCreateStruct = $locationService->newLocationCreateStruct($locationId);
116
                array_push($locations, $secondaryLocationCreateStruct);
117
            }
118
        }
119
120
        // create a draft using the content and location create struct and publish it
121
        $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...
122
        $content = $contentService->publishVersion($draft->versionInfo);
123
124
        $this->setReferences($content);
125
    }
126
127
    /**
128
     * Handle the content update migration action type
129
     *
130
     * @todo handle updating of more metadata fields
131
     */
132
    protected function update()
133
    {
134
        $this->loginUser();
135
136
        $contentService = $this->repository->getContentService();
137
        $contentTypeService = $this->repository->getContentTypeService();
138
139
        /*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...
140
            $objectId = $this->dsl['object_id'];
141
            if ($this->referenceResolver->isReference($objectId)) {
142
                $objectId = $this->referenceResolver->getReferenceValue($objectId);
143
            }
144
            $contentToUpdate = $contentService->loadContent($objectId);
145
            $contentInfo = $contentToUpdate->contentInfo;
146
        } else {
147
            $remoteId = $this->dsl['remote_id'];
148
            if ($this->referenceResolver->isReference($remoteId)) {
149
                $remoteId = $this->referenceResolver->getReferenceValue($remoteId);
150
            }
151
152
            //try {
153
                $contentInfo = $contentService->loadContentInfoByRemoteId($remoteId);
154
            // disabled in v2: we disallow this. For matching location-remote-id, use the 'match' keyword
155
            //} catch (\eZ\Publish\API\Repository\Exceptions\NotFoundException $e) {
156
            //    $location = $this->repository->getLocationService()->loadLocationByRemoteId($remoteId);
157
            //    $contentInfo = $location->contentInfo;
158
            //}
159
        }*/
160
161
        $contentCollection = $this->matchContents('update');
162
163
        if (count($contentCollection) > 1 && array_key_exists('references', $this->dsl)) {
164
            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");
165
        }
166
167
        $contentType = null;
168
169
        foreach ($contentCollection as $content) {
170
            $contentInfo = $content->contentInfo;
171
172
            if ($contentType == null) {
173
                $contentType = $contentTypeService->loadContentType($contentInfo->contentTypeId);
174
            }
175
176
            $contentUpdateStruct = $contentService->newContentUpdateStruct();
177
178
            if (array_key_exists('attributes', $this->dsl)) {
179
                $this->setFields($contentUpdateStruct, $this->dsl['attributes'], $contentType);
180
            }
181
182
            $draft = $contentService->createContentDraft($contentInfo);
183
            $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...
184
            $content = $contentService->publishVersion($draft->versionInfo);
185
186
            if (array_key_exists('new_remote_id', $this->dsl)) {
187
                // Update object remote ID
188
                $contentMetaDataUpdateStruct = $contentService->newContentMetadataUpdateStruct();
189
                $contentMetaDataUpdateStruct->remoteId = $this->dsl['new_remote_id'];
190
                $content = $contentService->updateContentMetadata($content->contentInfo, $contentMetaDataUpdateStruct);
191
192
                // Update main location remote ID
193
                // removed in v2: this is NOT generic!
194
                //$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...
195
                //$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...
196
                //$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...
197
                //$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...
198
                //$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...
199
            }
200
201
            $this->setReferences($contentCollection);
202
        }
203
    }
204
205
    /**
206
     * Handle the content delete migration action type
207
     */
208
    protected function delete()
209
    {
210
        $this->loginUser();
211
212
        $contentService = $this->repository->getContentService();
213
214
        $contentCollection = $this->matchContents('delete');
215
216
        foreach ($contentCollection as $content) {
217
            $contentService->deleteContent($content->contentInfo);
218
        }
219
    }
220
221
    /**
222
     * Helper function to set the fields of a ContentCreateStruct based on the DSL attribute settings.
223
     *
224
     * @param ContentCreateStruct|ContentUpdateStruct $createOrUpdateStruct
225
     * @param ContentType $contentType
226
     * @param array $fields
227
     */
228
    protected function setFields(&$createOrUpdateStruct, array $fields, ContentType $contentType)
229
    {
230
        foreach ($fields as $field) {
231
            // each $field is one key value pair
232
            // 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...
233
            $fieldIdentifier = key($field);
234
235
            $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...
236
237
            if (is_array($field[$fieldIdentifier])) {
238
                // Complex field needs special handling eg.: ezimage, ezbinaryfile
239
                $fieldValue = $this->getComplexFieldValue($field[$fieldIdentifier], $fieldType, $this->context);
240
            } else {
241
                // Primitive field eg.: ezstring, ezxml etc.
242
                $fieldValue = $this->getSingleFieldValue($field[$fieldIdentifier], $fieldType, $this->context);
243
            }
244
245
            $createOrUpdateStruct->setField($fieldIdentifier, $fieldValue, self::DEFAULT_LANGUAGE_CODE);
246
        }
247
    }
248
249
    /**
250
     * Create the field value for a primitive field
251
     * This function is needed to get past validation on Checkbox fieldtype (eZP bug)
252
     *
253
     * @param mixed $value
254
     * @param FieldType $fieldType
255
     * @param array $context
256
     * @throws \InvalidArgumentException
257
     * @return object
258
     */
259
    protected function getSingleFieldValue($value, FieldType $fieldType, 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...
260
    {
261
        switch ($fieldType->getFieldTypeIdentifier()) {
262
            case 'ezboolean':
263
                $fieldValue = new CheckboxValue(($value == 1) ? true : false);
264
                break;
265
            default:
266
                $fieldValue = $value;
267
        }
268
269
        if ($this->referenceResolver->isReference($value)) {
270
            $fieldValue = $this->referenceResolver->getReferenceValue($value);
271
        }
272
273
        return $fieldValue;
274
    }
275
276
    /**
277
     * Create the field value for a complex field eg.: ezimage, ezfile
278
     *
279
     * @param FieldType $fieldType
280
     * @param array $fieldValueArray
281
     * @param array $context
282
     * @return object
283
     */
284
    protected function getComplexFieldValue(array $fieldValueArray, FieldType $fieldType, array $context = array())
285
    {
286
        return $this->complexFieldManager->getComplexFieldValue($fieldType, $fieldValueArray, $context);
287
    }
288
289
    /**
290
     * Sets references to certain content attributes.
291
     * The Content Manager currently supports setting references to object_id and location_id
292
     *
293
     * @param \eZ\Publish\API\Repository\Values\Content\Content $content
294
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute
295
     * @return boolean
296
     *
297
     * @todo add support for other attributes: contentTypeId, contentTypeIdentifier, section, etc...
298
     */
299 View Code Duplication
    protected function setReferences($content)
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...
300
    {
301
        if (!array_key_exists('references', $this->dsl)) {
302
            return false;
303
        }
304
305
        foreach ($this->dsl['references'] as $reference) {
306
307
            switch ($reference['attribute']) {
308
                case 'object_id':
309
                case 'id':
310
                    $value = $content->id;
311
                    break;
312
                case 'location_id':
313
                    $value = $content->contentInfo->mainLocationId;
314
                    break;
315
                default:
316
                    throw new \InvalidArgumentException('Content Manager does not support setting references for attribute ' . $reference['attribute']);
317
            }
318
319
            $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...
320
        }
321
322
        return true;
323
    }
324
}
325