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

ObjectStateGroupManager::delete()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 14
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 14
loc 14
ccs 0
cts 9
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 1
crap 6
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);
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);
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
Bug introduced by
It seems like $groupsCollection defined by $this->matchObjectStateGroups('delete', $step) on line 114 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...
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
     * {@inheritdoc}
146
     * @param \eZ\Publish\API\Repository\Values\ObjectState\ObjectStateGroup|ObjectStateGroupCollection $objectStateGroup
147
     */
148 View Code Duplication
    protected function setReferences($objectStateGroup, $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...
149
    {
150
        if (!array_key_exists('references', $step->dsl)) {
151
            return false;
152
        }
153
154
        $references = $this->setReferencesCommon($objectStateGroup, $step->dsl['references']);
155
        $objectStateGroup = $this->insureSingleEntity($objectStateGroup, $references);
0 ignored issues
show
Unused Code introduced by
$objectStateGroup is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
156
    }
157
158
    /**
159
     * @param ObjectStateGroup $objectStateGroup
160
     * @param array $references the definitions of the references to set
161
     * @throws \InvalidArgumentException When trying to assign a reference to an unsupported attribute
162
     * @return array key: the reference names, values: the reference values
163
     */
164 View Code Duplication
    protected function getReferencesValues(ObjectStateGroup $objectStateGroup, 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...
165
    {
166
        $refs = array();
167
168
        foreach ($references as $reference) {
169
            switch ($reference['attribute']) {
170
                case 'object_state_group_id':
171
                case 'id':
172
                    $value = $objectStateGroup->id;
173
                    break;
174
                case 'object_state_group_identifier':
175
                case 'identifier':
176
                    $value = $objectStateGroup->id;
177
                    break;
178
                default:
179
                    throw new \InvalidArgumentException('Object State Group Manager does not support setting references for attribute ' . $reference['attribute']);
180
            }
181
182
            $refs[$reference['identifier']] = $value;
183
        }
184
185
        return $refs;
186
    }
187
188
    /**
189
     * @param array $matchCondition
190
     * @param string $mode
191
     * @param array $context
192
     * @throws \Exception
193
     * @return array
194
     */
195
    public function generateMigration(array $matchCondition, $mode, array $context = array())
196
    {
197
        $previousUserId = $this->loginUser($this->getAdminUserIdentifierFromContext($context));
198
        $objectStateGroupCollection = $this->objectStateGroupMatcher->match($matchCondition);
199
        $data = array();
200
201
        /** @var \eZ\Publish\API\Repository\Values\ObjectState\ObjectStateGroup $objectStateGroup */
202
        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...
203
204
            $groupData = array(
205
                'type' => reset($this->supportedStepTypes),
206
                'mode' => $mode,
207
            );
208
209
            switch ($mode) {
210
                case 'create':
211
                    $groupData = array_merge(
212
                        $groupData,
213
                        array(
214
                            'identifier' => $objectStateGroup->identifier,
215
                        )
216
                    );
217
                    break;
218 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...
219
                    $groupData = array_merge(
220
                        $groupData,
221
                        array(
222
                            'match' => array(
223
                                ObjectStateGroupMatcher::MATCH_OBJECTSTATEGROUP_IDENTIFIER => $objectStateGroup->identifier
224
                            ),
225
                            'identifier' => $objectStateGroup->identifier,
226
                        )
227
                    );
228
                    break;
229 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...
230
                    $groupData = array_merge(
231
                        $groupData,
232
                        array(
233
                            'match' => array(
234
                                ObjectStateGroupMatcher::MATCH_OBJECTSTATEGROUP_IDENTIFIER => $objectStateGroup->identifier
235
                            )
236
                        )
237
                    );
238
                    break;
239
                default:
240
                    throw new \Exception("Executor 'object_state_group' doesn't support mode '$mode'");
241
            }
242
243 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...
244
                $names = array();
245
                $descriptions = array();
246
                foreach($objectStateGroup->languageCodes as $languageCode) {
247
                    $names[$languageCode] =  $objectStateGroup->getName($languageCode);
248
                }
249
                foreach($objectStateGroup->languageCodes as $languageCode) {
250
                    $descriptions[$languageCode] =  $objectStateGroup->getDescription($languageCode);
251
                }
252
                $groupData = array_merge(
253
                    $groupData,
254
                    array(
255
                        'names' => $names,
256
                        'descriptions' => $descriptions,
257
                    )
258
                );
259
            }
260
261
            $data[] = $groupData;
262
        }
263
264
        $this->loginUser($previousUserId);
265
        return $data;
266
    }
267
}
268