forked from kaliop-uk/ezmigrationbundle
/
RoleManager.php
388 lines (329 loc) · 13.8 KB
/
RoleManager.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
<?php
namespace Kaliop\eZMigrationBundle\Core\Executor;
use eZ\Publish\API\Repository\Values\User\Role;
use eZ\Publish\API\Repository\RoleService;
use eZ\Publish\API\Repository\UserService;
use Kaliop\eZMigrationBundle\API\Collection\RoleCollection;
use Kaliop\eZMigrationBundle\API\MigrationGeneratorInterface;
use Kaliop\eZMigrationBundle\Core\Helper\LimitationConverter;
use Kaliop\eZMigrationBundle\Core\Matcher\RoleMatcher;
/**
* Handles role migrations.
*/
class RoleManager extends RepositoryExecutor implements MigrationGeneratorInterface
{
protected $supportedStepTypes = array('role');
protected $limitationConverter;
protected $roleMatcher;
public function __construct(RoleMatcher $roleMatcher, LimitationConverter $limitationConverter)
{
$this->roleMatcher = $roleMatcher;
$this->limitationConverter = $limitationConverter;
}
/**
* Method to handle the create operation of the migration instructions
*/
protected function create($step)
{
$roleService = $this->repository->getRoleService();
$userService = $this->repository->getUserService();
$roleCreateStruct = $roleService->newRoleCreateStruct($step->dsl['name']);
// Publish new role
$role = $roleService->createRole($roleCreateStruct);
if (is_callable(array($roleService, 'publishRoleDraft'))) {
$roleService->publishRoleDraft($role);
}
if (isset($step->dsl['policies'])) {
foreach ($step->dsl['policies'] as $key => $ymlPolicy) {
$this->addPolicy($role, $roleService, $ymlPolicy);
}
}
if (isset($step->dsl['assign'])) {
$this->assignRole($role, $roleService, $userService, $step->dsl['assign']);
}
$this->setReferences($role, $step);
return $role;
}
/**
* Method to handle the update operation of the migration instructions
*/
protected function update($step)
{
$roleCollection = $this->matchRoles('update', $step);
if (count($roleCollection) > 1 && isset($step->dsl['references'])) {
throw new \Exception("Can not execute Role update because multiple roles match, and a references section is specified in the dsl. References can be set when only 1 role matches");
}
if (count($roleCollection) > 1 && isset($step->dsl['new_name'])) {
throw new \Exception("Can not execute Role update because multiple roles match, and a new_name is specified in the dsl.");
}
$roleService = $this->repository->getRoleService();
$userService = $this->repository->getUserService();
/** @var \eZ\Publish\API\Repository\Values\User\Role $role */
foreach ($roleCollection as $key => $role) {
// Updating role name
if (isset($step->dsl['new_name'])) {
$update = $roleService->newRoleUpdateStruct();
$update->identifier = $step->dsl['new_name'];
$role = $roleService->updateRole($role, $update);
}
if (isset($step->dsl['policies'])) {
$ymlPolicies = $step->dsl['policies'];
// Removing all policies so we can add them back.
// TODO: Check and update policies instead of remove and add.
$policies = $role->getPolicies();
foreach ($policies as $policy) {
$roleService->deletePolicy($policy);
}
foreach ($ymlPolicies as $ymlPolicy) {
$this->addPolicy($role, $roleService, $ymlPolicy);
}
}
if (isset($step->dsl['assign'])) {
$this->assignRole($role, $roleService, $userService, $step->dsl['assign']);
}
$roleCollection[$key] = $role;
}
$this->setReferences($roleCollection, $step);
return $roleCollection;
}
/**
* Method to handle the delete operation of the migration instructions
*/
protected function delete($step)
{
$roleCollection = $this->matchRoles('delete', $step);
$this->setReferences($roleCollection, $step);
$roleService = $this->repository->getRoleService();
foreach ($roleCollection as $role) {
$roleService->deleteRole($role);
}
return $roleCollection;
}
/**
* @param string $action
* @return RoleCollection
* @throws \Exception
*/
protected function matchRoles($action, $step)
{
if (!isset($step->dsl['name']) && !isset($step->dsl['match'])) {
throw new \Exception("The name of a role or a match condition is required to $action it");
}
// Backwards compat
if (isset($step->dsl['match'])) {
$match = $step->dsl['match'];
} else {
$match = array('identifier' => $step->dsl['name']);
}
// convert the references passed in the match
$match = $this->resolveReferencesRecursively($match);
return $this->roleMatcher->match($match);
}
/**
* Set references to object attributes to be retrieved later.
*
* The Role Manager currently support setting references to role_ids.
*
* @param \eZ\Publish\API\Repository\Values\User\Role|RoleCollection $role
* @throws \InvalidArgumentException When trying to assign a reference to an unsupported attribute
* @return boolean
*/
protected function setReferences($role, $step)
{
if (!array_key_exists('references', $step->dsl)) {
return false;
}
$references = $this->setReferencesCommon($role, $step->dsl['references']);
$role = $this->insureSingleEntity($role, $references);
foreach ($references as $reference) {
switch ($reference['attribute']) {
case 'role_id':
case 'id':
$value = $role->id;
break;
case 'identifier':
case 'role_identifier':
$value = $role->identifier;
break;
default:
throw new \InvalidArgumentException('Role Manager does not support setting references for attribute ' . $reference['attribute']);
}
$overwrite = false;
if (isset($reference['overwrite'])) {
$overwrite = $reference['overwrite'];
}
$this->referenceResolver->addReference($reference['identifier'], $value, $overwrite);
}
return true;
}
/**
* @param array $matchCondition
* @param string $mode
* @param array $context
* @throws \Exception
* @return array
*/
public function generateMigration(array $matchCondition, $mode, array $context = array())
{
$previousUserId = $this->loginUser($this->getAdminUserIdentifierFromContext($context));
$roleCollection = $this->roleMatcher->match($matchCondition);
$data = array();
/** @var \eZ\Publish\API\Repository\Values\User\Role $role */
foreach ($roleCollection as $role) {
$roleData = array(
'type' => reset($this->supportedStepTypes),
'mode' => $mode
);
switch ($mode) {
case 'create':
$roleData = array_merge(
$roleData,
array(
'name' => $role->identifier
)
);
break;
case 'update':
case 'delete':
$roleData = array_merge(
$roleData,
array(
'match' => array(
RoleMatcher::MATCH_ROLE_IDENTIFIER => $role->identifier
)
)
);
break;
default:
throw new \Exception("Executor 'role' doesn't support mode '$mode'");
}
if ($mode != 'delete') {
$policies = array();
foreach ($role->getPolicies() as $policy) {
$limitations = array();
foreach ($policy->getLimitations() as $limitation) {
if ($limitation === null) {
throw new \Exception("The role contains NULL as limitation for policy {$policy->module}/{$policy->function}, we can not reliably generate its definition.");
}
$limitations[] = $this->limitationConverter->getLimitationArrayWithIdentifiers($limitation);
}
$policies[] = array(
'module' => $policy->module,
'function' => $policy->function,
'limitations' => $limitations
);
}
$roleData = array_merge(
$roleData,
array(
'policies' => $policies
)
);
}
$data[] = $roleData;
}
$this->loginUser($previousUserId);
return $data;
}
/**
* Create a new Limitation object based on the type and value in the $limitation array.
*
* <pre>
* $limitation = array(
* 'identifier' => Type of the limitation
* 'values' => array(Values to base the limitation on)
* )
* </pre>
*
* @param \eZ\Publish\API\Repository\RoleService $roleService
* @param array $limitation
* @return \eZ\Publish\API\Repository\Values\User\Limitation
*/
protected function createLimitation(RoleService $roleService, array $limitation)
{
$limitationType = $roleService->getLimitationType($limitation['identifier']);
$limitationValue = is_array($limitation['values']) ? $limitation['values'] : array($limitation['values']);
foreach ($limitationValue as $id => $value) {
$limitationValue[$id] = $this->referenceResolver->resolveReference($value);
}
$limitationValue = $this->limitationConverter->resolveLimitationValue($limitation['identifier'], $limitationValue);
return $limitationType->buildValue($limitationValue);
}
/**
* Assign a role to users and groups in the assignment array.
*
* <pre>
* $assignments = array(
* array(
* 'type' => 'user',
* 'ids' => array(user ids),
* 'limitation' => array(limitations)
* )
* )
* </pre>
*
* @param \eZ\Publish\API\Repository\Values\User\Role $role
* @param \eZ\Publish\API\Repository\RoleService $roleService
* @param \eZ\Publish\API\Repository\UserService $userService
* @param array $assignments
*/
protected function assignRole(Role $role, RoleService $roleService, UserService $userService, array $assignments)
{
foreach ($assignments as $assign) {
switch ($assign['type']) {
case 'user':
foreach ($assign['ids'] as $userId) {
$userId = $this->referenceResolver->resolveReference($userId);
$user = $userService->loadUser($userId);
if (!isset($assign['limitations'])) {
$roleService->assignRoleToUser($role, $user);
} else {
foreach ($assign['limitations'] as $limitation) {
$limitationObject = $this->createLimitation($roleService, $limitation);
$roleService->assignRoleToUser($role, $user, $limitationObject);
}
}
}
break;
case 'group':
foreach ($assign['ids'] as $groupId) {
$groupId = $this->referenceResolver->resolveReference($groupId);
$group = $userService->loadUserGroup($groupId);
if (!isset($assign['limitations'])) {
// q: why are we swallowing exceptions here ?
//try {
$roleService->assignRoleToUserGroup($role, $group);
//} catch (InvalidArgumentException $e) {}
} else {
foreach ($assign['limitations'] as $limitation) {
$limitationObject = $this->createLimitation($roleService, $limitation);
// q: why are we swallowing exceptions here ?
//try {
$roleService->assignRoleToUserGroup($role, $group, $limitationObject);
//} catch (InvalidArgumentException $e) {}
}
}
}
break;
}
}
}
/**
* Add new policies to the $role Role.
*
* @param \eZ\Publish\API\Repository\Values\User\Role $role
* @param \eZ\Publish\API\Repository\RoleService $roleService
* @param array $policy
*/
protected function addPolicy(Role $role, RoleService $roleService, array $policy)
{
$policyCreateStruct = $roleService->newPolicyCreateStruct($policy['module'], $policy['function']);
if (array_key_exists('limitations', $policy)) {
foreach ($policy['limitations'] as $limitation) {
$limitationObject = $this->createLimitation($roleService, $limitation);
$policyCreateStruct->addLimitation($limitationObject);
}
}
$roleService->addPolicy($role, $policyCreateStruct);
}
}