Completed
Push — master ( ba3b59...d7270b )
by Gaetano
16:37 queued 12:29
created

ObjectStateGroupManager::generateMigration()   C

Complexity

Conditions 8
Paths 8

Size

Total Lines 72
Code Lines 47

Duplication

Lines 38
Ratio 52.78 %

Code Coverage

Tests 37
CRAP Score 8.001

Importance

Changes 0
Metric Value
dl 38
loc 72
ccs 37
cts 38
cp 0.9737
rs 6.3883
c 0
b 0
f 0
cc 8
eloc 47
nc 8
nop 3
crap 8.001

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use Kaliop\eZMigrationBundle\API\Collection\ObjectStateGroupCollection;
6
use Kaliop\eZMigrationBundle\Core\Matcher\ObjectStateGroupMatcher;
7
use Kaliop\eZMigrationBundle\API\MigrationGeneratorInterface;
8
9
/**
10
 * Handles object-state-group migrations.
11
 */
12
class ObjectStateGroupManager extends RepositoryExecutor implements MigrationGeneratorInterface
13
{
14
    /**
15
     * @var array
16
     */
17
    protected $supportedStepTypes = array('object_state_group');
18
19
    /**
20
     * @var ObjectStateGroupMatcher
21
     */
22
    protected $objectStateGroupMatcher;
23
24
    /**
25
     * @param ObjectStateGroupMatcher $objectStateGroupMatcher
26
     */
27 73
    public function __construct(ObjectStateGroupMatcher $objectStateGroupMatcher)
28
    {
29 73
        $this->objectStateGroupMatcher = $objectStateGroupMatcher;
30 73
    }
31
32
    /**
33
     * Handles the create step of object state group migrations
34
     *
35
     * @todo add support for flexible defaultLanguageCode
36
     */
37 1
    protected function create($step)
38
    {
39 1 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...
40 1
            if (!isset($step->dsl[$key])) {
41 1
                throw new \Exception("The '$key' key is missing in a object state group creation definition");
42
            }
43
        }
44
45 1
        $objectStateService = $this->repository->getObjectStateService();
46
47 1
        $objectStateGroupIdentifier = $this->referenceResolver->resolveReference($step->dsl['identifier']);
48 1
        $objectStateGroupCreateStruct = $objectStateService->newObjectStateGroupCreateStruct($objectStateGroupIdentifier);
49 1
        $objectStateGroupCreateStruct->defaultLanguageCode = self::DEFAULT_LANGUAGE_CODE;
50
51 1
        foreach ($step->dsl['names'] as $languageCode => $name) {
52 1
            $objectStateGroupCreateStruct->names[$languageCode] = $name;
53
        }
54 1
        if (isset($step->dsl['descriptions'])) {
55 1
            foreach ($step->dsl['descriptions'] as $languageCode => $description) {
56 1
                $objectStateGroupCreateStruct->descriptions[$languageCode] = $description;
57
            }
58
        }
59
60 1
        $objectStateGroup = $objectStateService->createObjectStateGroup($objectStateGroupCreateStruct);
61
62 1
        $this->setReferences($objectStateGroup, $step);
63
64 1
        return $objectStateGroup;
65
    }
66
67
    /**
68
     * Handles the update step of object state group migrations
69
     *
70
     * @todo add support for defaultLanguageCode
71
     */
72 1 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...
73
    {
74 1
        $objectStateService = $this->repository->getObjectStateService();
75
76 1
        $groupsCollection = $this->matchObjectStateGroups('update', $step);
77
78 1
        if (count($groupsCollection) > 1 && isset($step->dsl['references'])) {
79
            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");
80
        }
81
82 1
        if (count($groupsCollection) > 1 && isset($step->dsl['identifier'])) {
83
            throw new \Exception("Can not execute Object State Group update because multiple groups match, and an identifier is specified in the dsl.");
84
        }
85
86 1
        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...
87 1
            $objectStateGroupUpdateStruct = $objectStateService->newObjectStateGroupUpdateStruct();
88
89 1
            if (isset($step->dsl['identifier'])) {
90 1
                $objectStateGroupUpdateStruct->identifier = $this->referenceResolver->resolveReference($step->dsl['identifier']);
91
            }
92 1
            if (isset($step->dsl['names'])) {
93
                foreach ($step->dsl['names'] as $languageCode => $name) {
94
                    $objectStateGroupUpdateStruct->names[$languageCode] = $name;
95
                }
96
            }
97 1
            if (isset($step->dsl['descriptions'])) {
98
                foreach ($step->dsl['descriptions'] as $languageCode => $description) {
99
                    $objectStateGroupUpdateStruct->descriptions[$languageCode] = $description;
100
                }
101
            }
102 1
            $objectStateGroup = $objectStateService->updateObjectStateGroup($objectStateGroup, $objectStateGroupUpdateStruct);
103
104 1
            $this->setReferences($objectStateGroup, $step);
105
        }
106
107 1
        return $groupsCollection;
108
    }
109
110
    /**
111
     * Handles the delete step of object state group migrations
112
     */
113 1 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...
114
    {
115 1
        $groupsCollection = $this->matchObjectStateGroups('delete', $step);
116
117 1
        $this->setReferences($groupsCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $groupsCollection defined by $this->matchObjectStateGroups('delete', $step) on line 115 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...
118
119 1
        $objectStateService = $this->repository->getObjectStateService();
120
121 1
        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...
122 1
            $objectStateService->deleteObjectStateGroup($objectStateGroup);
123
        }
124
125 1
        return $groupsCollection;
126
    }
127
128
    /**
129
     * @param string $action
130
     * @return ObjectStateGroupCollection
131
     * @throws \Exception
132
     */
133 1 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...
134
    {
135 1
        if (!isset($step->dsl['match'])) {
136
            throw new \Exception("A match condition is required to $action an object state group");
137
        }
138
139
        // convert the references passed in the match
140 1
        $match = $this->resolveReferencesRecursively($step->dsl['match']);
0 ignored issues
show
Deprecated Code introduced by
The method Kaliop\eZMigrationBundle...ReferencesRecursively() has been deprecated with message: will be moved into the reference resolver classes

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
141
142 1
        return $this->objectStateGroupMatcher->match($match);
143
    }
144
145
    /**
146
     * {@inheritdoc}
147
     * @param \eZ\Publish\API\Repository\Values\ObjectState\ObjectStateGroup|ObjectStateGroupCollection $objectStateGroup
148
     */
149 1 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...
150
    {
151 1
        if (!array_key_exists('references', $step->dsl)) {
152 1
            return false;
153
        }
154
155 1
        $references = $this->setReferencesCommon($objectStateGroup, $step->dsl['references']);
156 1
        $objectStateGroup = $this->insureSingleEntity($objectStateGroup, $references);
157
158 1
        foreach ($references as $reference) {
159 1
            switch ($reference['attribute']) {
160 1
                case 'object_state_group_id':
161 1
                case 'id':
162 1
                    $value = $objectStateGroup->id;
163 1
                    break;
164
                case 'object_state_group_identifier':
165
                case 'identifier':
166
                    $value = $objectStateGroup->id;
167
                    break;
168
                default:
169
                    throw new \InvalidArgumentException('Object State Group Manager does not support setting references for attribute ' . $reference['attribute']);
170
            }
171
172 1
            $overwrite = false;
173 1
            if (isset($reference['overwrite'])) {
174
                $overwrite = $reference['overwrite'];
175
            }
176 1
            $this->referenceResolver->addReference($reference['identifier'], $value, $overwrite);
177
        }
178
179 1
        return true;
180
    }
181
182
    /**
183
     * @param array $matchCondition
184
     * @param string $mode
185
     * @param array $context
186
     * @throws \Exception
187
     * @return array
188
     */
189 3
    public function generateMigration(array $matchCondition, $mode, array $context = array())
190
    {
191 3
        $previousUserId = $this->loginUser($this->getAdminUserIdentifierFromContext($context));
192 3
        $objectStateGroupCollection = $this->objectStateGroupMatcher->match($matchCondition);
193 3
        $data = array();
194
195
        /** @var \eZ\Publish\API\Repository\Values\ObjectState\ObjectStateGroup $objectStateGroup */
196 3
        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...
197
198
            $groupData = array(
199 3
                'type' => reset($this->supportedStepTypes),
200 3
                'mode' => $mode,
201
            );
202
203
            switch ($mode) {
204 3
                case 'create':
205 1
                    $groupData = array_merge(
206 1
                        $groupData,
207
                        array(
208 1
                            'identifier' => $objectStateGroup->identifier,
209
                        )
210
                    );
211 1
                    break;
212 2 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...
213 1
                    $groupData = array_merge(
214 1
                        $groupData,
215
                        array(
216
                            'match' => array(
217 1
                                ObjectStateGroupMatcher::MATCH_OBJECTSTATEGROUP_IDENTIFIER => $objectStateGroup->identifier
218
                            ),
219 1
                            'identifier' => $objectStateGroup->identifier,
220
                        )
221
                    );
222 1
                    break;
223 1 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...
224 1
                    $groupData = array_merge(
225 1
                        $groupData,
226
                        array(
227
                            'match' => array(
228 1
                                ObjectStateGroupMatcher::MATCH_OBJECTSTATEGROUP_IDENTIFIER => $objectStateGroup->identifier
229
                            )
230
                        )
231
                    );
232 1
                    break;
233
                default:
234
                    throw new \Exception("Executor 'object_state_group' doesn't support mode '$mode'");
235
            }
236
237 3 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...
238 2
                $names = array();
239 2
                $descriptions = array();
240 2
                foreach($objectStateGroup->languageCodes as $languageCode) {
241 2
                    $names[$languageCode] =  $objectStateGroup->getName($languageCode);
242
                }
243 2
                foreach($objectStateGroup->languageCodes as $languageCode) {
244 2
                    $descriptions[$languageCode] =  $objectStateGroup->getDescription($languageCode);
245
                }
246 2
                $groupData = array_merge(
247 2
                    $groupData,
248
                    array(
249 2
                        'names' => $names,
250 2
                        'descriptions' => $descriptions,
251
                    )
252
                );
253
            }
254
255 3
            $data[] = $groupData;
256
        }
257
258 3
        $this->loginUser($previousUserId);
259 3
        return $data;
260
    }
261
}
262