Completed
Pull Request — master (#133)
by Damian
20:49 queued 18:16
created

UserManager::update()   C

Complexity

Conditions 17
Paths 27

Size

Total Lines 74
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 17.039

Importance

Changes 0
Metric Value
dl 0
loc 74
ccs 37
cts 39
cp 0.9487
rs 5.3488
c 0
b 0
f 0
cc 17
eloc 39
nc 27
nop 1
crap 17.039

How to fix   Long Method    Complexity   

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\UserCollection;
6
use Kaliop\eZMigrationBundle\Core\Matcher\UserGroupMatcher;
7
use Kaliop\eZMigrationBundle\Core\Matcher\UserMatcher;
8
9
/**
10
 * Handles user migrations.
11
 */
12
class UserManager extends RepositoryExecutor
13
{
14
    protected $supportedStepTypes = array('user');
15
16
    protected $userMatcher;
17
18
    protected $userGroupMatcher;
19
20 70
    public function __construct(UserMatcher $userMatcher, UserGroupMatcher $userGroupMatcher)
21
    {
22 70
        $this->userMatcher = $userMatcher;
23 70
        $this->userGroupMatcher = $userGroupMatcher;
24 70
    }
25
26
    /**
27
     * Creates a user based on the DSL instructions.
28
     *
29
     * @todo allow setting extra profile attributes!
30
     */
31 2
    protected function create($step)
32
    {
33 2
        if (!isset($step->dsl['groups'])) {
34
            throw new \Exception('No user groups set to create user in.');
35
        }
36
37 2
        if (!is_array($step->dsl['groups'])) {
38
            $step->dsl['groups'] = array($step->dsl['groups']);
39
        }
40
41 2
        $userService = $this->repository->getUserService();
42 2
        $contentTypeService = $this->repository->getContentTypeService();
43
44 2
        $userGroups = array();
45 2 View Code Duplication
        foreach ($step->dsl['groups'] as $groupId) {
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...
46 2
            $groupId = $this->referenceResolver->resolveReference($groupId);
47 2
            $userGroup = $this->userGroupMatcher->matchOneByKey($groupId);
48
49
            // q: in which case can we have no group? And should we throw an exception?
50
            //if ($userGroup) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
51 2
                $userGroups[] = $userGroup;
52
            //}
53
        }
54
55
        // FIXME: Hard coding content type to user for now
56 2
        $userContentType = $contentTypeService->loadContentTypeByIdentifier($this->getUserContentType($step));
57
58 2
        $userCreateStruct = $userService->newUserCreateStruct(
59 2
            $step->dsl['username'],
60 2
            $step->dsl['email'],
61 2
            $step->dsl['password'],
62 2
            $this->getLanguageCode($step),
63 2
            $userContentType
64
        );
65 2
        $userCreateStruct->setField('first_name', $step->dsl['first_name']);
66 2
        $userCreateStruct->setField('last_name', $step->dsl['last_name']);
67
68
        // Create the user
69 2
        $user = $userService->createUser($userCreateStruct, $userGroups);
70
71 2
        $this->setReferences($user, $step);
72
73 2
        return $user;
74
    }
75
76
    /**
77
     * Method to handle the update operation of the migration instructions
78
     *
79
     * @todo allow setting extra profile attributes!
80
     */
81 1
    protected function update($step)
82
    {
83 1
        $userCollection = $this->matchUsers('user', $step);
84
85 1
        if (count($userCollection) > 1 && isset($step->dsl['references'])) {
86
            throw new \Exception("Can not execute User update because multiple user match, and a references section is specified in the dsl. References can be set when only 1 user matches");
87
        }
88
89 1
        if (count($userCollection) > 1 && isset($step->dsl['email'])) {
90
            throw new \Exception("Can not execute User update because multiple user match, and an email section is specified in the dsl.");
91
        }
92
93 1
        $userService = $this->repository->getUserService();
94
95 1
        foreach ($userCollection as $key => $user) {
0 ignored issues
show
Bug introduced by
The expression $userCollection of type object<Kaliop\eZMigratio...on\UserCollection>|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
97 1
            $userUpdateStruct = $userService->newUserUpdateStruct();
98
99 1
            if (isset($step->dsl['email'])) {
100 1
                $userUpdateStruct->email = $step->dsl['email'];
101
            }
102 1
            if (isset($step->dsl['password'])) {
103 1
                $userUpdateStruct->password = (string)$step->dsl['password'];
104
            }
105 1
            if (isset($step->dsl['enabled'])) {
106 1
                $userUpdateStruct->enabled = $step->dsl['enabled'];
107
            }
108
109 1
            $user = $userService->updateUser($user, $userUpdateStruct);
110
111 1
            if (isset($step->dsl['groups'])) {
112 1
                $groups = $step->dsl['groups'];
113
114 1
                if (!is_array($groups)) {
115 1
                    $groups = array($groups);
116
                }
117
118 1
                $assignedGroups = $userService->loadUserGroupsOfUser($user);
119
120 1
                $targetGroupIds = [];
121
                // Assigning new groups to the user
122 1
                foreach ($groups as $groupToAssignId) {
123 1
                    $groupId = $this->referenceResolver->resolveReference($groupToAssignId);
124 1
                    $groupToAssign = $this->userGroupMatcher->matchOneByKey($groupId);
125 1
                    $targetGroupIds[] = $groupToAssign->id;
126
127 1
                    $present = false;
128 1
                    foreach ($assignedGroups as $assignedGroup) {
129
                        // Make sure we assign the user only to groups he isn't already assigned to
130 1
                        if ($assignedGroup->id == $groupToAssign->id) {
131 1
                            $present = true;
132 1
                            break;
133
                        }
134
                    }
135 1
                    if (!$present) {
136 1
                        $userService->assignUserToUserGroup($user, $groupToAssign);
137
                    }
138
                }
139
140
                // Unassigning groups that are not in the list in the migration
141 1
                foreach ($assignedGroups as $assignedGroup) {
142 1
                    if (!in_array($assignedGroup->id, $targetGroupIds)) {
143 1
                        $userService->unAssignUserFromUserGroup($user, $assignedGroup);
144
                    }
145
                }
146
            }
147
148 1
            $userCollection[$key] = $user;
149
        }
150
151 1
        $this->setReferences($userCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $userCollection defined by $this->matchUsers('user', $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...
152
153 1
        return $userCollection;
154
    }
155
156
    /**
157
     * Method to handle the delete operation of the migration instructions
158
     */
159 2 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...
160
    {
161 2
        $userCollection = $this->matchUsers('delete', $step);
162
163 2
        $this->setReferences($userCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $userCollection defined by $this->matchUsers('delete', $step) on line 161 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...
164
165 2
        $userService = $this->repository->getUserService();
166
167 2
        foreach ($userCollection as $user) {
0 ignored issues
show
Bug introduced by
The expression $userCollection of type object<Kaliop\eZMigratio...on\UserCollection>|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...
168 2
            $userService->deleteUser($user);
169
        }
170
171 2
        return $userCollection;
172
    }
173
174
    /**
175
     * @param string $action
176
     * @return UserCollection
177
     * @throws \Exception
178
     */
179 2
    protected function matchUsers($action, $step)
180
    {
181 2
        if (!isset($step->dsl['id']) && !isset($step->dsl['user_id']) && !isset($step->dsl['email']) && !isset($step->dsl['username']) && !isset($step->dsl['match'])) {
182
            throw new \Exception("The id, email or username of a user or a match condition is required to $action it");
183
        }
184
185
        // Backwards compat
186 2
        if (isset($step->dsl['match'])) {
187 2
            $match = $step->dsl['match'];
188
        } else {
189 1
            $conds = array();
190 1
            if (isset($step->dsl['id'])) {
191 1
                $conds['id'] = $step->dsl['id'];
192
            }
193 1
            if (isset($step->dsl['user_id'])) {
194
                $conds['id'] = $step->dsl['user_id'];
195
            }
196 1
            if (isset($step->dsl['email'])) {
197
                $conds['email'] = $step->dsl['email'];
198
            }
199 1
            if (isset($step->dsl['username'])) {
200
                $conds['login'] = $step->dsl['username'];
201
            }
202 1
            $match = $conds;
203
        }
204
205
        // convert the references passed in the match
206 2
        $match = $this->resolveReferencesRecursively($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...
207
208 2
        return $this->userMatcher->match($match);
209
    }
210
211
    /**
212
     * Sets references to object attributes.
213
     *
214
     * The User manager currently only supports setting references to user_id.
215
     *
216
     * @param \eZ\Publish\API\Repository\Values\User\User|UserCollection $user
217
     * @throws \InvalidArgumentException when trying to set references to unsupported attributes
218
     * @return boolean
219
     */
220 2 View Code Duplication
    protected function setReferences($user, $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...
221
    {
222 2
        if (!array_key_exists('references', $step->dsl)) {
223 2
            return false;
224
        }
225
226 2
        $references = $this->setReferencesCommon($user, $step->dsl['references']);
227 2
        $user = $this->insureSingleEntity($user, $references);
228
229 2
        foreach ($references as $reference) {
230
231 2
            switch ($reference['attribute']) {
232 2
                case 'user_id':
233 2
                case 'id':
234 2
                    $value = $user->id;
235 2
                    break;
236
                case 'email':
237
                    $value = $user->email;
238
                    break;
239
                case 'enabled':
240
                    $value = $user->enabled;
241
                    break;
242
                case 'login':
243
                    $value = $user->login;
244
                    break;
245
                default:
246
                    throw new \InvalidArgumentException('User Manager does not support setting references for attribute ' . $reference['attribute']);
247
            }
248
249 2
            $overwrite = false;
250 2
            if (isset($reference['overwrite'])) {
251
                $overwrite = $reference['overwrite'];
252
            }
253 2
            $this->referenceResolver->addReference($reference['identifier'], $value, $overwrite);
254
        }
255
256 2
        return true;
257
    }
258
}
259