Completed
Push — master ( 290d49...5307dc )
by Gaetano
13:54 queued 06:53
created

ObjectStateGroupManager::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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
    protected $supportedActions = array('create', 'load', 'update', 'delete');
20
21
    /**
22
     * @var ObjectStateGroupMatcher
23
     */
24
    protected $objectStateGroupMatcher;
25
26
    /**
27
     * @param ObjectStateGroupMatcher $objectStateGroupMatcher
28
     */
29 80
    public function __construct(ObjectStateGroupMatcher $objectStateGroupMatcher)
30
    {
31 80
        $this->objectStateGroupMatcher = $objectStateGroupMatcher;
32 80
    }
33
34
    /**
35
     * Handles the create step of object state group migrations
36
     */
37 1
    protected function create($step)
38
    {
39 1
        foreach (array('names', 'identifier') as $key) {
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 = $this->getLanguageCode($step); // was: 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);
0 ignored issues
show
Documentation introduced by
$objectStateGroup is of type object<eZ\Publish\API\Re...State\ObjectStateGroup>, but the function expects a object<Object>|object<Ka...ion\AbstractCollection>.

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...
63
64 1
        return $objectStateGroup;
65
    }
66
67
    protected function load($step)
68
    {
69
        $groupsCollection = $this->matchObjectStateGroups('load', $step);
70
71
        $this->setReferences($groupsCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $groupsCollection defined by $this->matchObjectStateGroups('load', $step) on line 69 can be null; however, Kaliop\eZMigrationBundle...ecutor::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...
72
73
        return $groupsCollection;
74
    }
75
76
    /**
77
     * Handles the update step of object state group migrations
78
     *
79
     * @todo add support for defaultLanguageCode
80
     */
81 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...
82
    {
83 1
        $objectStateService = $this->repository->getObjectStateService();
84
85 1
        $groupsCollection = $this->matchObjectStateGroups('update', $step);
86
87 1
        if (count($groupsCollection) > 1 && isset($step->dsl['references'])) {
88
            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");
89
        }
90
91 1
        if (count($groupsCollection) > 1 && isset($step->dsl['identifier'])) {
92
            throw new \Exception("Can not execute Object State Group update because multiple groups match, and an identifier is specified in the dsl.");
93
        }
94
95 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...
96 1
            $objectStateGroupUpdateStruct = $objectStateService->newObjectStateGroupUpdateStruct();
97
98 1
            if (isset($step->dsl['identifier'])) {
99 1
                $objectStateGroupUpdateStruct->identifier = $this->referenceResolver->resolveReference($step->dsl['identifier']);
100
            }
101 1
            if (isset($step->dsl['names'])) {
102
                foreach ($step->dsl['names'] as $languageCode => $name) {
103
                    $objectStateGroupUpdateStruct->names[$languageCode] = $name;
104
                }
105
            }
106 1
            if (isset($step->dsl['descriptions'])) {
107
                foreach ($step->dsl['descriptions'] as $languageCode => $description) {
108
                    $objectStateGroupUpdateStruct->descriptions[$languageCode] = $description;
109
                }
110
            }
111 1
            $objectStateGroup = $objectStateService->updateObjectStateGroup($objectStateGroup, $objectStateGroupUpdateStruct);
112
113 1
            $this->setReferences($objectStateGroup, $step);
0 ignored issues
show
Documentation introduced by
$objectStateGroup is of type object<eZ\Publish\API\Re...State\ObjectStateGroup>, but the function expects a object<Object>|object<Ka...ion\AbstractCollection>.

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...
114
        }
115
116 1
        return $groupsCollection;
117
    }
118
119
    /**
120
     * Handles the delete step of object state group migrations
121
     */
122 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...
123
    {
124 1
        $groupsCollection = $this->matchObjectStateGroups('delete', $step);
125
126 1
        $this->setReferences($groupsCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $groupsCollection defined by $this->matchObjectStateGroups('delete', $step) on line 124 can be null; however, Kaliop\eZMigrationBundle...ecutor::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...
127
128 1
        $objectStateService = $this->repository->getObjectStateService();
129
130 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...
131 1
            $objectStateService->deleteObjectStateGroup($objectStateGroup);
132
        }
133
134 1
        return $groupsCollection;
135
    }
136
137
    /**
138
     * @param string $action
139
     * @return ObjectStateGroupCollection
140
     * @throws \Exception
141
     */
142 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...
143
    {
144 1
        if (!isset($step->dsl['match'])) {
145
            throw new \Exception("A match condition is required to $action an object state group");
146
        }
147
148
        // convert the references passed in the match
149 1
        $match = $this->resolveReferencesRecursively($step->dsl['match']);
150
151 1
        return $this->objectStateGroupMatcher->match($match);
152
    }
153
154
    /**
155
     * @param ObjectStateGroup $objectStateGroup
156
     * @param array $references the definitions of the references to set
157
     * @throws \InvalidArgumentException When trying to assign a reference to an unsupported attribute
158
     * @return array key: the reference names, values: the reference values
159
     */
160 1 View Code Duplication
    protected function getReferencesValues($objectStateGroup, array $references, $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...
161
    {
162 1
        $refs = array();
163
164 1
        foreach ($references as $reference) {
165 1
            switch ($reference['attribute']) {
166 1
                case 'object_state_group_id':
167 1
                case 'id':
168 1
                    $value = $objectStateGroup->id;
169 1
                    break;
170
                case 'object_state_group_identifier':
171
                case 'identifier':
172
                    $value = $objectStateGroup->id;
173
                    break;
174
                default:
175
                    throw new \InvalidArgumentException('Object State Group Manager does not support setting references for attribute ' . $reference['attribute']);
176
            }
177
178 1
            $refs[$reference['identifier']] = $value;
179
        }
180
181 1
        return $refs;
182
    }
183
184
    /**
185
     * @param array $matchCondition
186
     * @param string $mode
187
     * @param array $context
188
     * @throws \Exception
189
     * @return array
190
     */
191 3
    public function generateMigration(array $matchCondition, $mode, array $context = array())
192
    {
193 3
        $previousUserId = $this->loginUser($this->getAdminUserIdentifierFromContext($context));
194 3
        $objectStateGroupCollection = $this->objectStateGroupMatcher->match($matchCondition);
195 3
        $data = array();
196
197
        /** @var \eZ\Publish\API\Repository\Values\ObjectState\ObjectStateGroup $objectStateGroup */
198 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...
199
200
            $groupData = array(
201 3
                'type' => reset($this->supportedStepTypes),
202 3
                'mode' => $mode,
203
            );
204
205
            switch ($mode) {
206 3
                case 'create':
207 1
                    $groupData = array_merge(
208 1
                        $groupData,
209
                        array(
210 1
                            'identifier' => $objectStateGroup->identifier,
211
                        )
212
                    );
213 1
                    break;
214 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...
215 1
                    $groupData = array_merge(
216 1
                        $groupData,
217
                        array(
218
                            'match' => array(
219 1
                                ObjectStateGroupMatcher::MATCH_OBJECTSTATEGROUP_IDENTIFIER => $objectStateGroup->identifier
220
                            ),
221 1
                            'identifier' => $objectStateGroup->identifier,
222
                        )
223
                    );
224 1
                    break;
225 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...
226 1
                    $groupData = array_merge(
227 1
                        $groupData,
228
                        array(
229
                            'match' => array(
230 1
                                ObjectStateGroupMatcher::MATCH_OBJECTSTATEGROUP_IDENTIFIER => $objectStateGroup->identifier
231
                            )
232
                        )
233
                    );
234 1
                    break;
235
                default:
236
                    throw new \Exception("Executor 'object_state_group' doesn't support mode '$mode'");
237
            }
238
239 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...
240 2
                $names = array();
241 2
                $descriptions = array();
242 2
                foreach($objectStateGroup->languageCodes as $languageCode) {
243 2
                    $names[$languageCode] =  $objectStateGroup->getName($languageCode);
244
                }
245 2
                foreach($objectStateGroup->languageCodes as $languageCode) {
246 2
                    $descriptions[$languageCode] =  $objectStateGroup->getDescription($languageCode);
247
                }
248 2
                $groupData = array_merge(
249 2
                    $groupData,
250
                    array(
251 2
                        'names' => $names,
252 2
                        'descriptions' => $descriptions,
253
                    )
254
                );
255
            }
256
257 3
            $data[] = $groupData;
258
        }
259
260 3
        $this->loginUser($previousUserId);
261 3
        return $data;
262
    }
263
}
264