Completed
Push — master ( a0b010...baae4d )
by Gaetano
10:41
created

ObjectStateGroupManager::matchObjectStateGroups()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 21
Code Lines 11

Duplication

Lines 21
Ratio 100 %

Importance

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