Completed
Push — master ( 09cee1...75eab4 )
by Gaetano
06:21
created

ObjectStateManager::getReferencesValues()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 15

Duplication

Lines 22
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 22
loc 22
ccs 0
cts 19
cp 0
rs 8.6737
c 0
b 0
f 0
cc 5
eloc 15
nc 5
nop 2
crap 30
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use eZ\Publish\API\Repository\Values\ObjectState\ObjectState;
6
use Kaliop\eZMigrationBundle\Core\Matcher\ObjectStateGroupMatcher;
7
use Kaliop\eZMigrationBundle\Core\Matcher\ObjectStateMatcher;
8
use Kaliop\eZMigrationBundle\API\Collection\ObjectStateCollection;
9
use Kaliop\eZMigrationBundle\API\MigrationGeneratorInterface;
10
11
/**
12
 * Handles object-state migrations.
13
 */
14
class ObjectStateManager extends RepositoryExecutor implements MigrationGeneratorInterface
15
{
16
    /**
17
     * @var array
18
     */
19
    protected $supportedStepTypes = array('object_state');
20
21
    /**
22
     * @var ObjectStateMatcher
23
     */
24
    protected $objectStateMatcher;
25
26
    /**
27
     * @var ObjectStateGroupMatcher
28
     */
29
    protected $objectStateGroupMatcher;
30
31
    /**
32
     * @param ObjectStateMatcher      $objectStateMatcher
33
     * @param ObjectStateGroupMatcher $objectStateGroupMatcher
34
     */
35
    public function __construct(ObjectStateMatcher $objectStateMatcher, ObjectStateGroupMatcher $objectStateGroupMatcher)
36
    {
37
        $this->objectStateMatcher = $objectStateMatcher;
38
        $this->objectStateGroupMatcher = $objectStateGroupMatcher;
39
    }
40
41
    /**
42
     * Handles the create step of object state migrations.
43
     *
44
     * @throws \Exception
45
     */
46
    protected function create($step)
47
    {
48 View Code Duplication
        foreach (array('object_state_group', '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...
49
            if (!isset($step->dsl[$key])) {
50
                throw new \Exception("The '$key' key is missing in a object state creation definition");
51
            }
52
        }
53
54
        if (!count($step->dsl['names'])) {
55
            throw new \Exception('No object state names have been defined. Need to specify at least one to create the state.');
56
        }
57
58
        $objectStateService = $this->repository->getObjectStateService();
59
60
        $objectStateGroupId = $step->dsl['object_state_group'];
61
        $objectStateGroupId = $this->referenceResolver->resolveReference($objectStateGroupId);
62
        $objectStateGroup = $this->objectStateGroupMatcher->matchOneByKey($objectStateGroupId);
63
64
        $objectStateIdentifier = $this->referenceResolver->resolveReference($step->dsl['identifier']);
65
        $objectStateCreateStruct = $objectStateService->newObjectStateCreateStruct($objectStateIdentifier);
66
        $objectStateCreateStruct->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...
67
68
        foreach ($step->dsl['names'] as $languageCode => $name) {
69
            $objectStateCreateStruct->names[$languageCode] = $name;
70
        }
71
        if (isset($step->dsl['descriptions'])) {
72
            foreach ($step->dsl['descriptions'] as $languageCode => $description) {
73
                $objectStateCreateStruct->descriptions[$languageCode] = $description;
74
            }
75
        }
76
77
        $objectState = $objectStateService->createObjectState($objectStateGroup, $objectStateCreateStruct);
78
79
        $this->setReferences($objectState, $step);
0 ignored issues
show
Documentation introduced by
$objectState is of type object<eZ\Publish\API\Re...bjectState\ObjectState>, 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...
80
81
        return $objectState;
82
    }
83
84
    /**
85
     * Handles the update step of object state migrations.
86
     *
87
     * @throws \Exception
88
     */
89 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...
90
    {
91
        $stateCollection = $this->matchObjectStates('update', $step);
92
93
        if (count($stateCollection) > 1 && array_key_exists('references', $step->dsl)) {
94
            throw new \Exception("Can not execute Object State update because multiple states match, and a references section is specified in the dsl. References can be set when only 1 state matches");
95
        }
96
97
        if (count($stateCollection) > 1 && isset($step->dsl['identifier'])) {
98
            throw new \Exception("Can not execute Object State update because multiple states match, and an identifier is specified in the dsl.");
99
        }
100
101
        $objectStateService = $this->repository->getObjectStateService();
102
103
        foreach ($stateCollection as $state) {
0 ignored issues
show
Bug introduced by
The expression $stateCollection of type object<Kaliop\eZMigratio...ctStateCollection>|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...
104
            $objectStateUpdateStruct = $objectStateService->newObjectStateUpdateStruct();
105
106
            if (isset($step->dsl['identifier'])) {
107
                $objectStateUpdateStruct->identifier = $this->referenceResolver->resolveReference($step->dsl['identifier']);
108
            }
109
            if (isset($step->dsl['names'])) {
110
                foreach ($step->dsl['names'] as $name) {
111
                    $objectStateUpdateStruct->names[$name['languageCode']] = $name['name'];
112
                }
113
            }
114
            if (isset($step->dsl['descriptions'])) {
115
                foreach ($step->dsl['descriptions'] as $languageCode => $description) {
116
                    $objectStateUpdateStruct->descriptions[$languageCode] = $description;
117
                }
118
            }
119
            $state = $objectStateService->updateObjectState($state, $objectStateUpdateStruct);
120
121
            $this->setReferences($state, $step);
0 ignored issues
show
Documentation introduced by
$state is of type object<eZ\Publish\API\Re...bjectState\ObjectState>, 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...
122
        }
123
124
        return $stateCollection;
125
    }
126
127
    /**
128
     * Handles the deletion step of object state migrations.
129
     */
130 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...
131
    {
132
        $stateCollection = $this->matchObjectStates('delete', $step);
133
134
        $this->setReferences($stateCollection, $step);
0 ignored issues
show
Documentation introduced by
$stateCollection is of type object<Kaliop\eZMigratio...ctStateCollection>|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...
135
136
        $objectStateService = $this->repository->getObjectStateService();
137
138
        foreach ($stateCollection as $state) {
0 ignored issues
show
Bug introduced by
The expression $stateCollection of type object<Kaliop\eZMigratio...ctStateCollection>|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...
139
            $objectStateService->deleteObjectState($state);
140
        }
141
142
        return $stateCollection;
143
    }
144
145
    /**
146
     * @param string $action
147
     * @return ObjectStateCollection
148
     * @throws \Exception
149
     */
150 View Code Duplication
    protected function matchObjectStates($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...
151
    {
152
        if (!isset($step->dsl['match'])) {
153
            throw new \Exception("A match condition is required to $action an object state");
154
        }
155
156
        // convert the references passed in the match
157
        $match = $this->resolveReferencesRecursively($step->dsl['match']);
158
159
        return $this->objectStateMatcher->match($match);
160
    }
161
162
    /**
163
     * @param ObjectState $objectState
164
     * @param array $references the definitions of the references to set
165
     * @throws \InvalidArgumentException When trying to assign a reference to an unsupported attribute
166
     * @return array key: the reference names, values: the reference values
167
     */
168 View Code Duplication
    protected function getReferencesValues(ObjectState $objectState, array $references)
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...
169
    {
170
        $refs = array();
171
172
        foreach ($references as $reference) {
173
            switch ($reference['attribute']) {
174
                case 'object_state_id':
175
                case 'id':
176
                    $value = $objectState->id;
177
                    break;
178
                case 'priority':
179
                    $value = $objectState->priority;
180
                    break;
181
                default:
182
                    throw new \InvalidArgumentException('Object State Manager does not support setting references for attribute ' . $reference['attribute']);
183
            }
184
185
            $refs[$reference['identifier']] = $value;
186
        }
187
188
        return $refs;
189
    }
190
191
    /**
192
     * @param array $matchCondition
193
     * @param string $mode
194
     * @param array $context
195
     * @throws \Exception
196
     * @return array
197
     */
198
    public function generateMigration(array $matchCondition, $mode, array $context = array())
199
    {
200
        $previousUserId = $this->loginUser($this->getAdminUserIdentifierFromContext($context));
201
        $objectStateCollection = $this->objectStateMatcher->match($matchCondition);
202
        $data = array();
203
204
        /** @var \eZ\Publish\API\Repository\Values\ObjectState\ObjectState $objectState */
205
        foreach ($objectStateCollection as $objectState) {
0 ignored issues
show
Bug introduced by
The expression $objectStateCollection of type object<Kaliop\eZMigratio...ctStateCollection>|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...
206
207
            $groupData = array(
208
                'type' => reset($this->supportedStepTypes),
209
                'mode' => $mode,
210
            );
211
212
            switch ($mode) {
213
                case 'create':
214
                    $groupData = array_merge(
215
                        $groupData,
216
                        array(
217
                            'object_state_group' => $objectState->getObjectStateGroup()->identifier,
218
                            'identifier' => $objectState->identifier,
219
                        )
220
                    );
221
                    break;
222
                case 'update':
223
                    $groupData = array_merge(
224
                        $groupData,
225
                        array(
226
                            'match' => array(
227
                                ObjectStateMatcher::MATCH_OBJECTSTATE_IDENTIFIER =>
228
                                    $objectState->getObjectStateGroup()->identifier . '/' . $objectState->identifier
229
                            ),
230
                            'identifier' => $objectState->identifier,
231
                        )
232
                    );
233
                    break;
234
                case 'delete':
235
                    $groupData = array_merge(
236
                        $groupData,
237
                        array(
238
                            'match' => array(
239
                                ObjectStateMatcher::MATCH_OBJECTSTATE_IDENTIFIER =>
240
                                    $objectState->getObjectStateGroup()->identifier . '/' . $objectState->identifier
241
                            )
242
                        )
243
                    );
244
                    break;
245
                default:
246
                    throw new \Exception("Executor 'object_state_group' doesn't support mode '$mode'");
247
            }
248
249 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...
250
                $names = array();
251
                $descriptions = array();
252
                foreach($objectState->languageCodes as $languageCode) {
253
                    $names[$languageCode] =  $objectState->getName($languageCode);
254
                }
255
                foreach($objectState->languageCodes as $languageCode) {
256
                    $descriptions[$languageCode] =  $objectState->getDescription($languageCode);
257
                }
258
                $groupData = array_merge(
259
                    $groupData,
260
                    array(
261
                        'names' => $names,
262
                        'descriptions' => $descriptions,
263
                    )
264
                );
265
            }
266
267
            $data[] = $groupData;
268
        }
269
270
        $this->loginUser($previousUserId);
271
        return $data;
272
    }
273
}
274