Completed
Push — master ( 68da2d...d119ba )
by Gaetano
07:21
created

UserGroupManager   B

Complexity

Total Complexity 34

Size/Duplication

Total Lines 220
Duplicated Lines 39.09 %

Coupling/Cohesion

Components 1
Dependencies 15

Test Coverage

Coverage 88.04%

Importance

Changes 0
Metric Value
wmc 34
lcom 1
cbo 15
dl 86
loc 220
ccs 81
cts 92
cp 0.8804
rs 8.4332
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B create() 10 43 6
B update() 0 55 9
A delete() 14 14 2
C matchUserGroups() 23 23 7
C setReferences() 31 31 8
A setSection() 8 8 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use eZ\Publish\API\Repository\Values\Content\Content;
6
use Kaliop\eZMigrationBundle\Core\Matcher\UserGroupMatcher;
7
use Kaliop\eZMigrationBundle\API\Collection\UserGroupCollection;
8
use Kaliop\eZMigrationBundle\Core\Matcher\RoleMatcher;
9
use Kaliop\eZMigrationBundle\Core\Matcher\SectionMatcher;
10
11
/**
12
 * Handles user-group migrations.
13
 */
14
class UserGroupManager extends RepositoryExecutor
15
{
16
    protected $supportedStepTypes = array('user_group');
17 1
18
    protected $userGroupMatcher;
19 1
    protected $roleMatcher;
20
    protected $sectionMatcher;
21 1
22 1
    public function __construct(UserGroupMatcher $userGroupMatcher, RoleMatcher $roleMatcher, SectionMatcher $sectionMatcher)
23
    {
24
        $this->userGroupMatcher = $userGroupMatcher;
25
        $this->roleMatcher = $roleMatcher;
26 1
        $this->sectionMatcher = $sectionMatcher;
27
    }
28 1
29
    /**
30 1
     * Method to handle the create operation of the migration instructions
31 1
     */
32
    protected function create($step)
33 1
    {
34 1
        $userService = $this->repository->getUserService();
35 1
36
        $parentGroupId = $step->dsl['parent_group_id'];
37 1
        $parentGroupId = $this->referenceResolver->resolveReference($parentGroupId);
38
        $parentGroup = $this->userGroupMatcher->matchOneByKey($parentGroupId);
39 1
40 1
        $contentType = $this->repository->getContentTypeService()->loadContentTypeByIdentifier("user_group");
41 1
42 1
        $userGroupCreateStruct = $userService->newUserGroupCreateStruct($this->getLanguageCode($step), $contentType);
43 1
        $userGroupCreateStruct->setField('name', $step->dsl['name']);
44 1
45
        if (isset($step->dsl['remote_id'])) {
46
            $userGroupCreateStruct->remoteId = $step->dsl['remote_id'];
47
        }
48 1
49 1
        if (isset($step->dsl['description'])) {
50 1
            $userGroupCreateStruct->setField('description', $step->dsl['description']);
51
        }
52
53 View Code Duplication
        if (isset($step->dsl['section'])) {
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...
54
            $sectionKey = $this->referenceResolver->resolveReference($step->dsl['section']);
55 1
            $section = $this->sectionMatcher->matchOneByKey($sectionKey);
56 1
            $userGroupCreateStruct->sectionId = $section->id;
57
        }
58
59
        $userGroup = $userService->createUserGroup($userGroupCreateStruct, $parentGroup);
60
61
        if (isset($step->dsl['roles'])) {
62
            $roleService = $this->repository->getRoleService();
63 1
            // we support both Ids and Identifiers
64 View Code Duplication
            foreach ($step->dsl['roles'] as $roleId) {
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...
65 1
                $roleId = $this->referenceResolver->resolveReference($roleId);
66
                $role = $this->roleMatcher->matchOneByKey($roleId);
67
                $roleService->assignRoleToUserGroup($role, $userGroup);
68
            }
69 1
        }
70 1
71
        $this->setReferences($userGroup, $step);
72 1
73 1
        return $userGroup;
74 1
    }
75 1
76
    /**
77 1
     * Method to handle the update operation of the migration instructions
78
     *
79
     * @throws \Exception When the ID of the user group is missing from the migration definition.
80 1
     */
81
    protected function update($step)
82
    {
83 1
        $userGroupCollection = $this->matchUserGroups('update', $step);
84
85 1
        if (count($userGroupCollection) > 1 && isset($step->dsl['references'])) {
86 1
            throw new \Exception("Can not execute Group update because multiple groups match, and a references section is specified in the dsl. References can be set when only 1 group matches");
87 1
        }
88
89 1
        $userService = $this->repository->getUserService();
90 1
        $contentService = $this->repository->getContentService();
91 1
92
        foreach ($userGroupCollection as $key => $userGroup) {
0 ignored issues
show
Bug introduced by
The expression $userGroupCollection of type object<Kaliop\eZMigratio...erGroupCollection>|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...
93 1
94
            /** @var $updateStruct \eZ\Publish\API\Repository\Values\User\UserGroupUpdateStruct */
95 1
            $updateStruct = $userService->newUserGroupUpdateStruct();
96
97 1
            /** @var $contentUpdateStruct \eZ\Publish\API\Repository\Values\Content\ContentUpdateStruct */
98 1
            $contentUpdateStruct = $contentService->newContentUpdateStruct();
99 1
100
            if (isset($step->dsl['name'])) {
101
                $contentUpdateStruct->setField('name', $step->dsl['name']);
102
            }
103 1
104
            if (isset($step->dsl['remote_id'])) {
105
                $contentUpdateStruct->remoteId = $step->dsl['remote_id'];
106 1
            }
107 1
108
            if (isset($step->dsl['description'])) {
109 1
                $contentUpdateStruct->setField('description', $step->dsl['description']);
110 1
            }
111
112
            $updateStruct->contentUpdateStruct = $contentUpdateStruct;
113
114
            $userGroup = $userService->updateUserGroup($userGroup, $updateStruct);
115
116
            if (isset($step->dsl['parent_group_id'])) {
117 1
                $parentGroupId = $step->dsl['parent_group_id'];
118
                $parentGroupId = $this->referenceResolver->resolveReference($parentGroupId);
119 1
                $newParentGroup = $this->userGroupMatcher->matchOneByKey($parentGroupId);
120
121
                // Move group to new parent
122
                $userService->moveUserGroup($userGroup, $newParentGroup);
123 1
            }
124
125
            if (isset($step->dsl['section'])) {
126
                $this->setSection($userGroup, $step->dsl['section']);
127 1
            }
128
129
            $userGroupCollection[$key] = $userGroup;
130 1
        }
131 1
132 1
        $this->setReferences($userGroupCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $userGroupCollection defined by $this->matchUserGroups('update', $step) on line 83 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...
133 1
134
        return $userGroupCollection;
135 1
    }
136
137 1
    /**
138 1
     * Method to handle the delete operation of the migration instructions
139 1
     *
140
     * @throws \Exception When there are no groups specified for deletion.
141 1
     */
142 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...
143 1
    {
144 1
        $userGroupCollection = $this->matchUserGroups('delete', $step);
145
146
        $this->setReferences($userGroupCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $userGroupCollection defined by $this->matchUserGroups('delete', $step) on line 144 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...
147
148
        $userService = $this->repository->getUserService();
149
150
        foreach ($userGroupCollection as $userGroup) {
0 ignored issues
show
Bug introduced by
The expression $userGroupCollection of type object<Kaliop\eZMigratio...erGroupCollection>|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...
151
            $userService->deleteUserGroup($userGroup);
152
        }
153 1
154
        return $userGroupCollection;
155 1
    }
156 1
157 1
    /**
158
     * @param string $action
159 1
     * @return UserGroupCollection
160
     * @throws \Exception
161 1
     */
162 1 View Code Duplication
    protected function matchUserGroups($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...
163 1
    {
164 1
        if (!isset($step->dsl['id']) && !isset($step->dsl['group']) && !isset($step->dsl['match'])) {
165 1
            throw new \Exception("The id of a user group or a match condition is required to $action it");
166 1
        }
167
168
        // Backwards compat
169 1
        if (isset($step->dsl['match'])) {
170
            $match = $step->dsl['match'];
171 1
        } else {
172 1
            if (isset($step->dsl['id'])) {
173
                $match = array('id' => $step->dsl['id']);
174 1
            }
175
            if (isset($step->dsl['group'])) {
176
                $match = array('id' => $step->dsl['group']);
177
            }
178
        }
179
180
        // convert the references passed in the match
181
        $match = $this->resolveReferencesRecursively($match);
0 ignored issues
show
Bug introduced by
The variable $match does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
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...
182
183
        return $this->userGroupMatcher->match($match);
184
    }
185
186
    /**
187
     * Set references defined in the DSL for use in another step during the migrations.
188
     *
189
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute
190
     * @param \eZ\Publish\API\Repository\Values\User\UserGroup|UserGroupCollection $userGroup
191
     * @return boolean
192
     */
193 View Code Duplication
    protected function setReferences($userGroup, $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...
194
    {
195
        if (!array_key_exists('references', $step->dsl)) {
196
            return false;
197
        }
198
199
        $this->setReferencesCommon($userGroup, $step);
200
        $userGroup = $this->insureSingleEntity($userGroup, $step);
201
202
        foreach ($step->dsl['references'] as $reference) {
203
204
            switch ($reference['attribute']) {
205
                case 'object_id':
206
                case 'content_id':
207
                case 'user_group_id':
208
                case 'id':
209
                    $value = $userGroup->id;
210
                    break;
211
                default:
212
                    throw new \InvalidArgumentException('User Group Manager does not support setting references for attribute ' . $reference['attribute']);
213
            }
214
215
            $overwrite = false;
216
            if (isset($reference['overwrite'])) {
217
                $overwrite = $reference['overwrite'];
218
            }
219
            $this->referenceResolver->addReference($reference['identifier'], $value, $overwrite);
220
        }
221
222
        return true;
223
    }
224
225 View Code Duplication
    protected function setSection(Content $content, $sectionKey)
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...
226
    {
227
        $sectionKey = $this->referenceResolver->resolveReference($sectionKey);
228
        $section = $this->sectionMatcher->matchOneByKey($sectionKey);
229
230
        $sectionService = $this->repository->getSectionService();
231
        $sectionService->assignSection($content->contentInfo, $section);
232
    }
233
}
234