Passed
Push — master ( 2b8f81...145d48 )
by Gaetano
10:22 queued 05:19
created

UserManager::load()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 9
ccs 0
cts 6
cp 0
crap 2
rs 10
c 0
b 0
f 0
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\API\Exception\InvalidStepDefinitionException;
8
use Kaliop\eZMigrationBundle\Core\Matcher\UserGroupMatcher;
9
use Kaliop\eZMigrationBundle\Core\Matcher\UserMatcher;
10
11
/**
12
 * Handles user migrations.
13
 */
14
class UserManager extends RepositoryExecutor
15
{
16
    protected $supportedStepTypes = array('user');
17
    protected $supportedActions = array('create', 'load', 'update', 'delete');
18
19
    protected $userMatcher;
20
21
    protected $userGroupMatcher;
22
23
    public function __construct(UserMatcher $userMatcher, UserGroupMatcher $userGroupMatcher)
24
    {
25
        $this->userMatcher = $userMatcher;
26
        $this->userGroupMatcher = $userGroupMatcher;
27
    }
28
29
    /**
30
     * Creates a user based on the DSL instructions.
31
     *
32
     * @todo allow setting extra profile attributes!
33
     */
34
    protected function create($step)
35
    {
36
        if (!isset($step->dsl['groups'])) {
37
            throw new InvalidStepDefinitionException('No user groups set to create user in.');
38
        }
39
40
        if (!is_array($step->dsl['groups'])) {
41
            $step->dsl['groups'] = array($step->dsl['groups']);
42
        }
43
44
        $userService = $this->repository->getUserService();
45
        $contentTypeService = $this->repository->getContentTypeService();
46
47
        $userGroups = array();
48
        foreach ($step->dsl['groups'] as $groupId) {
49
            $groupId = $this->referenceResolver->resolveReference($groupId);
50
            $userGroup = $this->userGroupMatcher->matchOneByKey($groupId);
51
52
            // q: in which case can we have no group? And should we throw an exception?
53
            //if ($userGroup) {
54
                $userGroups[] = $userGroup;
55
            //}
56
        }
57
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
        if (isset($step->dsl['roles'])) {
74
            $roleService = $this->repository->getRoleService();
75
            // we support both Ids and Identifiers
76
            foreach ($step->dsl['roles'] as $roleId) {
77
                $roleId = $this->referenceResolver->resolveReference($roleId);
78
                $role = $this->roleMatcher->matchOneByKey($roleId);
0 ignored issues
show
Bug Best Practice introduced by
The property roleMatcher does not exist on Kaliop\eZMigrationBundle\Core\Executor\UserManager. Did you maybe forget to declare it?
Loading history...
79
                $roleService->assignRoleToUser($role, $user);
80
            }
81
        }
82
83
        $this->setReferences($user, $step);
84
85
        return $user;
86
    }
87
88
    protected function load($step)
89
    {
90
        $userCollection = $this->matchUsers('load', $step);
91
92
        $this->validateResultsCount($userCollection, $step);
93
94
        $this->setReferences($userCollection, $step);
95
96
        return $userCollection;
97
    }
98
99
    /**
100
     * Method to handle the update operation of the migration instructions
101
     *
102
     * @todo allow setting extra profile attributes!
103
     */
104
    protected function update($step)
105
    {
106
        $userCollection = $this->matchUsers('user', $step);
107
108
        $this->validateResultsCount($userCollection, $step);
109
110
        if (count($userCollection) > 1 && isset($step->dsl['email'])) {
111
            throw new \Exception("Can not execute User update because multiple users match, and an email section is specified in the dsl.");
112
        }
113
114
        $userService = $this->repository->getUserService();
115
116
        foreach ($userCollection as $key => $user) {
117
118
            $userUpdateStruct = $userService->newUserUpdateStruct();
119
120
            if (isset($step->dsl['email'])) {
121
                $userUpdateStruct->email = $this->referenceResolver->resolveReference($step->dsl['email']);
122
            }
123
            if (isset($step->dsl['password'])) {
124
                $userUpdateStruct->password = (string)$this->referenceResolver->resolveReference($step->dsl['password']);
125
            }
126
            if (isset($step->dsl['enabled'])) {
127
                $userUpdateStruct->enabled = $this->referenceResolver->resolveReference($step->dsl['enabled']);
128
            }
129
130
            $user = $userService->updateUser($user, $userUpdateStruct);
131
132
            if (isset($step->dsl['groups'])) {
133
                $groups = $step->dsl['groups'];
134
135
                if (!is_array($groups)) {
136
                    $groups = array($groups);
137
                }
138
139
                $assignedGroups = $userService->loadUserGroupsOfUser($user);
140
141
                $targetGroupIds = [];
142
                // Assigning new groups to the user
143
                foreach ($groups as $groupToAssignId) {
144
                    $groupId = $this->referenceResolver->resolveReference($groupToAssignId);
145
                    $groupToAssign = $this->userGroupMatcher->matchOneByKey($groupId);
146
                    $targetGroupIds[] = $groupToAssign->id;
147
148
                    $present = false;
149
                    foreach ($assignedGroups as $assignedGroup) {
150
                        // Make sure we assign the user only to groups he isn't already assigned to
151
                        if ($assignedGroup->id == $groupToAssign->id) {
152
                            $present = true;
153
                            break;
154
                        }
155
                    }
156
                    if (!$present) {
157
                        $userService->assignUserToUserGroup($user, $groupToAssign);
158
                    }
159
                }
160
161
                // Unassigning groups that are not in the list in the migration
162
                foreach ($assignedGroups as $assignedGroup) {
163
                    if (!in_array($assignedGroup->id, $targetGroupIds)) {
164
                        $userService->unAssignUserFromUserGroup($user, $assignedGroup);
165
                    }
166
                }
167
            }
168
169
            $userCollection[$key] = $user;
170
        }
171
172
        $this->setReferences($userCollection, $step);
173
174
        return $userCollection;
175
    }
176
177
    /**
178
     * Method to handle the delete operation of the migration instructions
179
     */
180
    protected function delete($step)
181
    {
182
        $userCollection = $this->matchUsers('delete', $step);
183
184
        $this->validateResultsCount($userCollection, $step);
185
186
        $this->setReferences($userCollection, $step);
187
188
        $userService = $this->repository->getUserService();
189
190
        foreach ($userCollection as $user) {
191
            $userService->deleteUser($user);
192
        }
193
194
        return $userCollection;
195
    }
196
197
    /**
198
     * @param string $action
199
     * @return UserCollection
200
     * @throws \Exception
201
     */
202
    protected function matchUsers($action, $step)
203
    {
204
        if (!isset($step->dsl['id']) && !isset($step->dsl['user_id']) && !isset($step->dsl['email']) && !isset($step->dsl['username']) && !isset($step->dsl['match'])) {
205
            throw new InvalidStepDefinitionException("The id, email or username of a user or a match condition is required to $action it");
206
        }
207
208
        // Backwards compat
209
        if (isset($step->dsl['match'])) {
210
            $match = $step->dsl['match'];
211
        } else {
212
            $conds = array();
213
            if (isset($step->dsl['id'])) {
214
                $conds['id'] = $step->dsl['id'];
215
            }
216
            if (isset($step->dsl['user_id'])) {
217
                $conds['id'] = $step->dsl['user_id'];
218
            }
219
            if (isset($step->dsl['email'])) {
220
                $conds['email'] = $step->dsl['email'];
221
            }
222
            if (isset($step->dsl['username'])) {
223
                $conds['login'] = $step->dsl['username'];
224
            }
225
            $match = $conds;
226
        }
227
228
        // convert the references passed in the match
229
        $match = $this->resolveReferencesRecursively($match);
230
231
        $tolerateMisses = isset($step->dsl['match_tolerate_misses']) ? $this->referenceResolver->resolveReference($step->dsl['match_tolerate_misses']) : false;
232
233
        return $this->userMatcher->match($match, $tolerateMisses);
234
    }
235
236
    /**
237
     * @param User $user
238
     * @param array $references the definitions of the references to set
239
     * @throws InvalidStepDefinitionException
240
     * @return array key: the reference names, values: the reference values
241
     *
242
     * @todo allow setting refs to all the attributes that can be gotten for Contents
243
     */
244
    protected function getReferencesValues($user, array $references, $step)
245
    {
246
        $refs = array();
247
248
        foreach ($references as $key => $reference) {
249
250
            $reference = $this->parseReferenceDefinition($key, $reference);
251
252
            switch ($reference['attribute']) {
253
                case 'user_id':
254
                case 'id':
255
                    $value = $user->id;
256
                    break;
257
                case 'email':
258
                    $value = $user->email;
259
                    break;
260
                case 'enabled':
261
                    $value = $user->enabled;
262
                    break;
263
                case 'login':
264
                    $value = $user->login;
265
                    break;
266
                case 'groups_ids':
267
                    $value = [];
268
                    $userService = $this->repository->getUserService();
269
                    $userGroups = $userService->loadUserGroupsOfUser($user);
270
                    foreach ($userGroups as $userGroup) {
271
                        $value[] = $userGroup->id;
272
                    }
273
                    break;
274
                default:
275
                    throw new InvalidStepDefinitionException('User Manager does not support setting references for attribute ' . $reference['attribute']);
276
            }
277
278
            $refs[$reference['identifier']] = $value;
279
        }
280
281
        return $refs;
282
    }
283
}
284