Completed
Push — master ( 2686f5...0602f1 )
by Gaetano
09:57
created

UserManager::create()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 44

Duplication

Lines 9
Ratio 20.45 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 9
loc 44
ccs 0
cts 29
cp 0
rs 9.216
c 0
b 0
f 0
cc 4
nc 5
nop 1
crap 20
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use eZ\Publish\API\Repository\Values\User\User;
6
use Kaliop\eZMigrationBundle\API\Collection\UserCollection;
7
use Kaliop\eZMigrationBundle\Core\Matcher\UserGroupMatcher;
8
use Kaliop\eZMigrationBundle\Core\Matcher\UserMatcher;
9
10
/**
11
 * Handles user migrations.
12
 */
13
class UserManager extends RepositoryExecutor
14
{
15
    protected $supportedStepTypes = array('user');
16
    protected $supportedActions = array('create', 'load', 'update', 'delete');
17
18
    protected $userMatcher;
19
20
    protected $userGroupMatcher;
21
22
    public function __construct(UserMatcher $userMatcher, UserGroupMatcher $userGroupMatcher)
23
    {
24
        $this->userMatcher = $userMatcher;
25
        $this->userGroupMatcher = $userGroupMatcher;
26
    }
27
28
    /**
29
     * Creates a user based on the DSL instructions.
30
     *
31
     * @todo allow setting extra profile attributes!
32
     */
33
    protected function create($step)
34
    {
35
        if (!isset($step->dsl['groups'])) {
36
            throw new \Exception('No user groups set to create user in.');
37
        }
38
39
        if (!is_array($step->dsl['groups'])) {
40
            $step->dsl['groups'] = array($step->dsl['groups']);
41
        }
42
43
        $userService = $this->repository->getUserService();
44
        $contentTypeService = $this->repository->getContentTypeService();
45
46
        $userGroups = array();
47 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...
48
            $groupId = $this->referenceResolver->resolveReference($groupId);
49
            $userGroup = $this->userGroupMatcher->matchOneByKey($groupId);
50
51
            // q: in which case can we have no group? And should we throw an exception?
52
            //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...
53
                $userGroups[] = $userGroup;
54
            //}
55
        }
56
57
        // FIXME: Hard coding content type to user for now
58
        $userContentType = $contentTypeService->loadContentTypeByIdentifier($this->getUserContentType($step));
59
60
        $userCreateStruct = $userService->newUserCreateStruct(
61
            $this->referenceResolver->resolveReference($step->dsl['username']),
62
            $this->referenceResolver->resolveReference($step->dsl['email']),
63
            $this->referenceResolver->resolveReference($step->dsl['password']),
64
            $this->getLanguageCode($step),
65
            $userContentType
66
        );
67
        $userCreateStruct->setField('first_name', $this->referenceResolver->resolveReference($step->dsl['first_name']));
68
        $userCreateStruct->setField('last_name', $this->referenceResolver->resolveReference($step->dsl['last_name']));
69
70
        // Create the user
71
        $user = $userService->createUser($userCreateStruct, $userGroups);
72
73
        $this->setReferences($user, $step);
0 ignored issues
show
Documentation introduced by
$user is of type object<eZ\Publish\API\Re...itory\Values\User\User>, 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...
74
75
        return $user;
76
    }
77
78
    protected function load($step)
79
    {
80
        $userCollection = $this->matchUsers('load', $step);
81
82
        $this->setReferences($userCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $userCollection defined by $this->matchUsers('load', $step) on line 80 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...
83
84
        return $userCollection;
85
    }
86
87
    /**
88
     * Method to handle the update operation of the migration instructions
89
     *
90
     * @todo allow setting extra profile attributes!
91
     */
92
    protected function update($step)
93
    {
94
        $userCollection = $this->matchUsers('user', $step);
95
96
        if (count($userCollection) > 1 && isset($step->dsl['references'])) {
97
            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");
98
        }
99
100
        if (count($userCollection) > 1 && isset($step->dsl['email'])) {
101
            throw new \Exception("Can not execute User update because multiple user match, and an email section is specified in the dsl.");
102
        }
103
104
        $userService = $this->repository->getUserService();
105
106
        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...
107
108
            $userUpdateStruct = $userService->newUserUpdateStruct();
109
110 View Code Duplication
            if (isset($step->dsl['email'])) {
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...
111
                $userUpdateStruct->email = $this->referenceResolver->resolveReference($step->dsl['email']);
112
            }
113 View Code Duplication
            if (isset($step->dsl['password'])) {
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...
114
                $userUpdateStruct->password = (string)$this->referenceResolver->resolveReference($step->dsl['password']);
115
            }
116 View Code Duplication
            if (isset($step->dsl['enabled'])) {
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...
117
                $userUpdateStruct->enabled = $this->referenceResolver->resolveReference($step->dsl['enabled']);
118
            }
119
120
            $user = $userService->updateUser($user, $userUpdateStruct);
121
122
            if (isset($step->dsl['groups'])) {
123
                $groups = $step->dsl['groups'];
124
125
                if (!is_array($groups)) {
126
                    $groups = array($groups);
127
                }
128
129
                $assignedGroups = $userService->loadUserGroupsOfUser($user);
130
131
                $targetGroupIds = [];
132
                // Assigning new groups to the user
133
                foreach ($groups as $groupToAssignId) {
134
                    $groupId = $this->referenceResolver->resolveReference($groupToAssignId);
135
                    $groupToAssign = $this->userGroupMatcher->matchOneByKey($groupId);
136
                    $targetGroupIds[] = $groupToAssign->id;
137
138
                    $present = false;
139
                    foreach ($assignedGroups as $assignedGroup) {
140
                        // Make sure we assign the user only to groups he isn't already assigned to
141
                        if ($assignedGroup->id == $groupToAssign->id) {
142
                            $present = true;
143
                            break;
144
                        }
145
                    }
146
                    if (!$present) {
147
                        $userService->assignUserToUserGroup($user, $groupToAssign);
148
                    }
149
                }
150
151
                // Unassigning groups that are not in the list in the migration
152
                foreach ($assignedGroups as $assignedGroup) {
153
                    if (!in_array($assignedGroup->id, $targetGroupIds)) {
154
                        $userService->unAssignUserFromUserGroup($user, $assignedGroup);
155
                    }
156
                }
157
            }
158
159
            $userCollection[$key] = $user;
160
        }
161
162
        $this->setReferences($userCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $userCollection defined by $this->matchUsers('user', $step) on line 94 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...
163
164
        return $userCollection;
165
    }
166
167
    /**
168
     * Method to handle the delete operation of the migration instructions
169
     */
170 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...
171
    {
172
        $userCollection = $this->matchUsers('delete', $step);
173
174
        $this->setReferences($userCollection, $step);
0 ignored issues
show
Bug introduced by
It seems like $userCollection defined by $this->matchUsers('delete', $step) on line 172 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...
175
176
        $userService = $this->repository->getUserService();
177
178
        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...
179
            $userService->deleteUser($user);
180
        }
181
182
        return $userCollection;
183
    }
184
185
    /**
186
     * @param string $action
187
     * @return UserCollection
188
     * @throws \Exception
189
     */
190
    protected function matchUsers($action, $step)
191
    {
192
        if (!isset($step->dsl['id']) && !isset($step->dsl['user_id']) && !isset($step->dsl['email']) && !isset($step->dsl['username']) && !isset($step->dsl['match'])) {
193
            throw new \Exception("The id, email or username of a user or a match condition is required to $action it");
194
        }
195
196
        // Backwards compat
197
        if (isset($step->dsl['match'])) {
198
            $match = $step->dsl['match'];
199
        } else {
200
            $conds = array();
201
            if (isset($step->dsl['id'])) {
202
                $conds['id'] = $step->dsl['id'];
203
            }
204
            if (isset($step->dsl['user_id'])) {
205
                $conds['id'] = $step->dsl['user_id'];
206
            }
207
            if (isset($step->dsl['email'])) {
208
                $conds['email'] = $step->dsl['email'];
209
            }
210
            if (isset($step->dsl['username'])) {
211
                $conds['login'] = $step->dsl['username'];
212
            }
213
            $match = $conds;
214
        }
215
216
        // convert the references passed in the match
217
        $match = $this->resolveReferencesRecursively($match);
218
219
        return $this->userMatcher->match($match);
220
    }
221
222
    /**
223
     * @param User $user
224
     * @param array $references the definitions of the references to set
225
     * @throws \InvalidArgumentException When trying to assign a reference to an unsupported attribute
226
     * @return array key: the reference names, values: the reference values
227
     */
228
    protected function getReferencesValues($user, array $references, $step)
229
    {
230
        $refs = array();
231
232
        foreach ($references as $reference) {
233
234
            switch ($reference['attribute']) {
235
                case 'user_id':
236
                case 'id':
237
                    $value = $user->id;
238
                    break;
239
                case 'email':
240
                    $value = $user->email;
241
                    break;
242
                case 'enabled':
243
                    $value = $user->enabled;
244
                    break;
245
                case 'login':
246
                    $value = $user->login;
247
                    break;
248 View Code Duplication
                case 'groups_ids':
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
                    $value = [];
250
                    $userService = $this->repository->getUserService();
251
                    $limit = 100;
252
                    $offset = 0;
253
                    do {
254
                        $userGroups = $userService->loadUserGroupsOfUser($user, $offset, $limit);
0 ignored issues
show
Unused Code introduced by
The call to UserService::loadUserGroupsOfUser() has too many arguments starting with $offset.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
255
                        foreach ($userGroups as $userGroup) {
256
                            $value[] = $userGroup->id;
257
                        }
258
                    } while (count($userService));
259
                    break;
260
                default:
261
                    throw new \InvalidArgumentException('User Manager does not support setting references for attribute ' . $reference['attribute']);
262
            }
263
264
            $refs[$reference['identifier']] = $value;
265
        }
266
267
        return $refs;
268
    }
269
}
270