Completed
Push — master ( 4484df...ecad36 )
by Gaetano
07:23
created

ObjectStateGroupManager::getReferencesValues()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 23
c 0
b 0
f 0
ccs 0
cts 20
cp 0
rs 8.5906
cc 6
eloc 16
nc 6
nop 2
crap 42
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use eZ\Publish\API\Repository\Values\ObjectState\ObjectStateGroup;
6
use Kaliop\eZMigrationBundle\API\Collection\ObjectStateGroupCollection;
7
use Kaliop\eZMigrationBundle\Core\Matcher\ObjectStateGroupMatcher;
8
use Kaliop\eZMigrationBundle\API\MigrationGeneratorInterface;
9
10
/**
11
 * Handles object-state-group migrations.
12
 */
13
class ObjectStateGroupManager extends RepositoryExecutor implements MigrationGeneratorInterface
14
{
15
    /**
16
     * @var array
17
     */
18
    protected $supportedStepTypes = array('object_state_group');
19
20
    /**
21
     * @var ObjectStateGroupMatcher
22
     */
23
    protected $objectStateGroupMatcher;
24
25
    /**
26
     * @param ObjectStateGroupMatcher $objectStateGroupMatcher
27
     */
28
    public function __construct(ObjectStateGroupMatcher $objectStateGroupMatcher)
29
    {
30
        $this->objectStateGroupMatcher = $objectStateGroupMatcher;
31
    }
32
33
    /**
34
     * Handles the create step of object state group migrations
35
     */
36
    protected function create($step)
37
    {
38 View Code Duplication
        foreach (array('names', 'identifier') as $key) {
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...
39
            if (!isset($step->dsl[$key])) {
40
                throw new \Exception("The '$key' key is missing in a object state group creation definition");
41
            }
42
        }
43
44
        $objectStateService = $this->repository->getObjectStateService();
45
46
        $objectStateGroupIdentifier = $this->referenceResolver->resolveReference($step->dsl['identifier']);
47
        $objectStateGroupCreateStruct = $objectStateService->newObjectStateGroupCreateStruct($objectStateGroupIdentifier);
48
        $objectStateGroupCreateStruct->defaultLanguageCode = $this->getLanguageCode($step); // was: self::DEFAULT_LANGUAGE_CODE;
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
49
50
        foreach ($step->dsl['names'] as $languageCode => $name) {
51
            $objectStateGroupCreateStruct->names[$languageCode] = $name;
52
        }
53
        if (isset($step->dsl['descriptions'])) {
54
            foreach ($step->dsl['descriptions'] as $languageCode => $description) {
55
                $objectStateGroupCreateStruct->descriptions[$languageCode] = $description;
56
            }
57
        }
58
59
        $objectStateGroup = $objectStateService->createObjectStateGroup($objectStateGroupCreateStruct);
60
61
        $this->setReferences($objectStateGroup, $step);
0 ignored issues
show
Documentation introduced by
$objectStateGroup is of type object<eZ\Publish\API\Re...State\ObjectStateGroup>, but the function expects a object<Object>|object<Ka...ctCollectionCollection>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
62
63
        return $objectStateGroup;
64
    }
65
66
    /**
67
     * Handles the update step of object state group migrations
68
     *
69
     * @todo add support for defaultLanguageCode
70
     */
71 View Code Duplication
    protected function update($step)
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...
72
    {
73
        $objectStateService = $this->repository->getObjectStateService();
74
75
        $groupsCollection = $this->matchObjectStateGroups('update', $step);
76
77
        if (count($groupsCollection) > 1 && isset($step->dsl['references'])) {
78
            throw new \Exception("Can not execute Object State Group update because multiple groups match, and a references section is specified in the dsl. References can be set when only 1 state group matches");
79
        }
80
81
        if (count($groupsCollection) > 1 && isset($step->dsl['identifier'])) {
82
            throw new \Exception("Can not execute Object State Group update because multiple groups match, and an identifier is specified in the dsl.");
83
        }
84
85
        foreach ($groupsCollection as $objectStateGroup) {
0 ignored issues
show
Bug introduced by
The expression $groupsCollection of type object<Kaliop\eZMigratio...teGroupCollection>|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...
86
            $objectStateGroupUpdateStruct = $objectStateService->newObjectStateGroupUpdateStruct();
87
88
            if (isset($step->dsl['identifier'])) {
89
                $objectStateGroupUpdateStruct->identifier = $this->referenceResolver->resolveReference($step->dsl['identifier']);
90
            }
91
            if (isset($step->dsl['names'])) {
92
                foreach ($step->dsl['names'] as $languageCode => $name) {
93
                    $objectStateGroupUpdateStruct->names[$languageCode] = $name;
94
                }
95
            }
96
            if (isset($step->dsl['descriptions'])) {
97
                foreach ($step->dsl['descriptions'] as $languageCode => $description) {
98
                    $objectStateGroupUpdateStruct->descriptions[$languageCode] = $description;
99
                }
100
            }
101
            $objectStateGroup = $objectStateService->updateObjectStateGroup($objectStateGroup, $objectStateGroupUpdateStruct);
102
103
            $this->setReferences($objectStateGroup, $step);
0 ignored issues
show
Documentation introduced by
$objectStateGroup is of type object<eZ\Publish\API\Re...State\ObjectStateGroup>, but the function expects a object<Object>|object<Ka...ctCollectionCollection>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
104
        }
105
106
        return $groupsCollection;
107
    }
108
109
    /**
110
     * Handles the delete step of object state group migrations
111
     */
112 View Code Duplication
    protected function delete($step)
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...
113
    {
114
        $groupsCollection = $this->matchObjectStateGroups('delete', $step);
115
116
        $this->setReferences($groupsCollection, $step);
0 ignored issues
show
Documentation introduced by
$groupsCollection is of type object<Kaliop\eZMigratio...teGroupCollection>|null, but the function expects a object<Object>|object<Ka...ctCollectionCollection>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
117
118
        $objectStateService = $this->repository->getObjectStateService();
119
120
        foreach ($groupsCollection as $objectStateGroup) {
0 ignored issues
show
Bug introduced by
The expression $groupsCollection of type object<Kaliop\eZMigratio...teGroupCollection>|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...
121
            $objectStateService->deleteObjectStateGroup($objectStateGroup);
122
        }
123
124
        return $groupsCollection;
125
    }
126
127
    /**
128
     * @param string $action
129
     * @return ObjectStateGroupCollection
130
     * @throws \Exception
131
     */
132 View Code Duplication
    protected function matchObjectStateGroups($action, $step)
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...
133
    {
134
        if (!isset($step->dsl['match'])) {
135
            throw new \Exception("A match condition is required to $action an object state group");
136
        }
137
138
        // convert the references passed in the match
139
        $match = $this->resolveReferencesRecursively($step->dsl['match']);
140
141
        return $this->objectStateGroupMatcher->match($match);
142
    }
143
144
    /**
145
     * @param ObjectStateGroup $objectStateGroup
146
     * @param array $references the definitions of the references to set
147
     * @throws \InvalidArgumentException When trying to assign a reference to an unsupported attribute
148
     * @return array key: the reference names, values: the reference values
149
     */
150
    protected function getReferencesValues($objectStateGroup, array $references)
151
    {
152
        $refs = array();
153
154
        foreach ($references as $reference) {
155
            switch ($reference['attribute']) {
156
                case 'object_state_group_id':
157
                case 'id':
158
                    $value = $objectStateGroup->id;
159
                    break;
160
                case 'object_state_group_identifier':
161
                case 'identifier':
162
                    $value = $objectStateGroup->id;
163
                    break;
164
                default:
165
                    throw new \InvalidArgumentException('Object State Group Manager does not support setting references for attribute ' . $reference['attribute']);
166
            }
167
168
            $refs[$reference['identifier']] = $value;
169
        }
170
171
        return $refs;
172
    }
173
174
    /**
175
     * @param array $matchCondition
176
     * @param string $mode
177
     * @param array $context
178
     * @throws \Exception
179
     * @return array
180
     */
181
    public function generateMigration(array $matchCondition, $mode, array $context = array())
182
    {
183
        $previousUserId = $this->loginUser($this->getAdminUserIdentifierFromContext($context));
184
        $objectStateGroupCollection = $this->objectStateGroupMatcher->match($matchCondition);
185
        $data = array();
186
187
        /** @var \eZ\Publish\API\Repository\Values\ObjectState\ObjectStateGroup $objectStateGroup */
188
        foreach ($objectStateGroupCollection as $objectStateGroup) {
0 ignored issues
show
Bug introduced by
The expression $objectStateGroupCollection of type object<Kaliop\eZMigratio...teGroupCollection>|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...
189
190
            $groupData = array(
191
                'type' => reset($this->supportedStepTypes),
192
                'mode' => $mode,
193
            );
194
195
            switch ($mode) {
196
                case 'create':
197
                    $groupData = array_merge(
198
                        $groupData,
199
                        array(
200
                            'identifier' => $objectStateGroup->identifier,
201
                        )
202
                    );
203
                    break;
204 View Code Duplication
                case 'update':
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...
205
                    $groupData = array_merge(
206
                        $groupData,
207
                        array(
208
                            'match' => array(
209
                                ObjectStateGroupMatcher::MATCH_OBJECTSTATEGROUP_IDENTIFIER => $objectStateGroup->identifier
210
                            ),
211
                            'identifier' => $objectStateGroup->identifier,
212
                        )
213
                    );
214
                    break;
215 View Code Duplication
                case 'delete':
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...
216
                    $groupData = array_merge(
217
                        $groupData,
218
                        array(
219
                            'match' => array(
220
                                ObjectStateGroupMatcher::MATCH_OBJECTSTATEGROUP_IDENTIFIER => $objectStateGroup->identifier
221
                            )
222
                        )
223
                    );
224
                    break;
225
                default:
226
                    throw new \Exception("Executor 'object_state_group' doesn't support mode '$mode'");
227
            }
228
229 View Code Duplication
            if ($mode != 'delete') {
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...
230
                $names = array();
231
                $descriptions = array();
232
                foreach($objectStateGroup->languageCodes as $languageCode) {
233
                    $names[$languageCode] =  $objectStateGroup->getName($languageCode);
234
                }
235
                foreach($objectStateGroup->languageCodes as $languageCode) {
236
                    $descriptions[$languageCode] =  $objectStateGroup->getDescription($languageCode);
237
                }
238
                $groupData = array_merge(
239
                    $groupData,
240
                    array(
241
                        'names' => $names,
242
                        'descriptions' => $descriptions,
243
                    )
244
                );
245
            }
246
247
            $data[] = $groupData;
248
        }
249
250
        $this->loginUser($previousUserId);
251
        return $data;
252
    }
253
}
254