Completed
Push — master ( baae4d...638cc8 )
by Gaetano
10:40
created

ObjectStateManager::generateMigration()   C

Complexity

Conditions 8
Paths 8

Size

Total Lines 75
Code Lines 50

Duplication

Lines 40
Ratio 53.33 %

Importance

Changes 0
Metric Value
dl 40
loc 75
rs 6.2413
c 0
b 0
f 0
cc 8
eloc 50
nc 8
nop 2

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