Completed
Pull Request — master (#91)
by
unknown
08:50
created

RoleManager::create()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5.0488

Importance

Changes 0
Metric Value
dl 0
loc 27
ccs 14
cts 16
cp 0.875
rs 8.439
c 0
b 0
f 0
cc 5
eloc 14
nc 8
nop 0
crap 5.0488
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use eZ\Publish\API\Repository\Values\User\Role;
6
use eZ\Publish\API\Repository\RoleService;
7
use eZ\Publish\API\Repository\UserService;
8
use eZ\Publish\API\Repository\Exceptions\InvalidArgumentException;
9
use Kaliop\eZMigrationBundle\API\Collection\RoleCollection;
10
use Kaliop\eZMigrationBundle\API\MigrationGeneratorInterface;
11
use Kaliop\eZMigrationBundle\Core\Helper\LimitationConverter;
12
use Kaliop\eZMigrationBundle\Core\Matcher\RoleMatcher;
13
14
/**
15
 * Handles the role migration definitions.
16
 */
17
class RoleManager extends RepositoryExecutor implements MigrationGeneratorInterface
18
{
19
    protected $supportedStepTypes = array('role');
20 20
21
    protected $limitationConverter;
22 20
    protected $roleMatcher;
23 20
24
    public function __construct(RoleMatcher $roleMatcher, LimitationConverter $limitationConverter)
25
    {
26
        $this->roleMatcher = $roleMatcher;
27
        $this->limitationConverter = $limitationConverter;
28 1
    }
29
30 1
    /**
31 1
     * Method to handle the create operation of the migration instructions
32
     */
33 1
    protected function create()
34
    {
35
        $roleService = $this->repository->getRoleService();
36 1
        $userService = $this->repository->getUserService();
37
38 1
        $roleCreateStruct = $roleService->newRoleCreateStruct($this->dsl['name']);
39 1
40 1
        // Publish new role
41 1
        $role = $roleService->createRole($roleCreateStruct);
42 1
        if (is_callable(array($roleService, 'publishRoleDraft'))) {
43 1
            $roleService->publishRoleDraft($role);
0 ignored issues
show
Bug introduced by
The method publishRoleDraft() does not seem to exist on object<eZ\Publish\API\Repository\RoleService>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
44
        }
45 1
46
        if (isset($this->dsl['policies'])) {
47
            foreach($this->dsl['policies'] as $key => $ymlPolicy) {
48
                $this->addPolicy($role, $roleService, $ymlPolicy);
49 1
            }
50 1
        }
51
52
        if (isset($this->dsl['assign'])) {
53
            $this->assignRole($role, $roleService, $userService, $this->dsl['assign']);
54
        }
55 1
56
        $this->setReferences($role);
57 1
58 1
        return $role;
59
    }
60 1
61
    /**
62 1
     * Method to handle the update operation of the migration instructions
63
     */
64
    protected function update()
65 1
    {
66
        $roleCollection = $this->matchRoles('update');
67
68
        if (count($roleCollection) > 1 && isset($this->dsl['references'])) {
69
            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");
70
        }
71 1
72 1
        if (count($roleCollection) > 1 && isset($this->dsl['new_name'])) {
73
            throw new \Exception("Can not execute Role update because multiple roles match, and a new_name is specified in the dsl.");
74
        }
75
76 1
        $roleService = $this->repository->getRoleService();
77 1
        $userService = $this->repository->getUserService();
78
79 1
        /** @var \eZ\Publish\API\Repository\Values\User\Role $role */
80
        foreach ($roleCollection as $key => $role) {
0 ignored issues
show
Bug introduced by
The expression $roleCollection of type object<Kaliop\eZMigratio...on\RoleCollection>|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...
81 1
82 1
            // Updating role name
83 1
            if (isset($this->dsl['new_name'])) {
84 1
                $update = $roleService->newRoleUpdateStruct();
85
                $update->identifier = $this->dsl['new_name'];
86 1
                $role = $roleService->updateRole($role, $update);
87 1
            }
88 1
89
            if (isset($this->dsl['policies'])) {
90 1
                $ymlPolicies = $this->dsl['policies'];
91 1
92
                // Removing all policies so we can add them back.
93 1
                // TODO: Check and update policies instead of remove and add.
94
                $policies = $role->getPolicies();
95
                foreach($policies as $policy) {
96
                    $roleService->deletePolicy($policy);
97
                }
98 1
99
                foreach($ymlPolicies as $ymlPolicy) {
100
                    $this->addPolicy($role, $roleService, $ymlPolicy);
101 1
                }
102
            }
103 1
104 1
            if (isset($this->dsl['assign'])) {
105 1
                $this->assignRole($role, $roleService, $userService, $this->dsl['assign']);
106 1
            }
107 1
108
            $roleCollection[$key] = $role;
109
        }
110
111
        $this->setReferences($roleCollection);
0 ignored issues
show
Bug introduced by
It seems like $roleCollection defined by $this->matchRoles('update') on line 66 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...
112
113
        return $roleCollection;
114
    }
115
116
    /**
117
     * Method to handle the delete operation of the migration instructions
118 1
     */
119
    protected function delete()
120 1
    {
121 1
        $roleCollection = $this->matchRoles('delete');
122
123
        $roleService = $this->repository->getRoleService();
124 1
125 1
        foreach ($roleCollection as $role) {
0 ignored issues
show
Bug introduced by
The expression $roleCollection of type object<Kaliop\eZMigratio...on\RoleCollection>|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...
126 1
            $roleService->deleteRole($role);
127 1
        }
128 1
129 1
        return $roleCollection;
130 1
    }
131 1
132 1
    /**
133 1
     * @param string $action
134
     * @return RoleCollection
135 1
     * @throws \Exception
136 1
     */
137 View Code Duplication
    protected function matchRoles($action)
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...
138 1
    {
139 1
        if (!isset($this->dsl['name']) && !isset($this->dsl['match'])) {
140
            throw new \Exception("The name of a role or a match condition is required to $action it.");
141 1
        }
142
143
        // Backwards compat
144
        if (!isset($this->dsl['match'])) {
145
            $this->dsl['match'] = array('identifier' => $this->dsl['name']);
146
        }
147
148
        $match = $this->dsl['match'];
149
150
        // convert the references passed in the match
151
        foreach ($match as $condition => $values) {
152
            if (is_array($values)) {
153
                foreach ($values as $position => $value) {
154
                    $match[$condition][$position] = $this->referenceResolver->resolveReference($value);
155
                }
156
            } else {
157
                $match[$condition] = $this->referenceResolver->resolveReference($values);
158 1
            }
159
        }
160 1
161
        return $this->roleMatcher->match($match);
162 1
    }
163
164 1
    /**
165 1
     * Set references to object attributes to be retrieved later.
166
     *
167
     * The Role Manager currently support setting references to role_ids.
168
     *
169 1
     * @param \eZ\Publish\API\Repository\Values\User\Role|RoleCollection $role
170 1
     * @throws \InvalidArgumentException When trying to assign a reference to an unsupported attribute
171 1
     * @return boolean
172
     */
173 View Code Duplication
    protected function setReferences($role)
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...
174
    {
175
        if (!array_key_exists('references', $this->dsl)) {
176
            return false;
177
        }
178
179
        if ($role instanceof RoleCollection) {
180
            if (count($role) > 1) {
181
                throw new \InvalidArgumentException('Role Manager does not support setting references for creating/updating of multiple roles');
182
            }
183
            $role = reset($role);
184
        }
185
186
        foreach ($this->dsl['references'] as $reference) {
187
            switch ($reference['attribute']) {
188
                case 'role_id':
189
                case 'id':
190
                    $value = $role->id;
191
                    break;
192 1
                case 'identifier':
193
                case 'role_identifier':
194 1
                    $value = $role->identifier;
195 1
                    break;
196 1
                default:
197 1
                    throw new \InvalidArgumentException('Role Manager does not support setting references for attribute ' . $reference['attribute']);
198 1
            }
199
200 1
            $this->referenceResolver->addReference($reference['identifier'], $value);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Kaliop\eZMigrationBundle...erenceResolverInterface as the method addReference() does only exist in the following implementations of said interface: Kaliop\eZMigrationBundle...ver\ChainPrefixResolver, Kaliop\eZMigrationBundle...ver\ChainRegexpResolver, Kaliop\eZMigrationBundle...eResolver\ChainResolver, Kaliop\eZMigrationBundle...CustomReferenceResolver.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
201
        }
202
203 1
        return true;
204 1
    }
205 1
206 1
    /**
207
     * Create a new Limitation object based on the type and value in the $limitation array.
208 1
     *
209 1
     * <pre>
210
     * $limitation = array(
211
     *  'identifier' => Type of the limitation
212
     *  'values' => array(Values to base the limitation on)
213
     * )
214
     * </pre>
215
     *
216
     * @param \eZ\Publish\API\Repository\RoleService $roleService
217
     * @param array $limitation
218
     * @return \eZ\Publish\API\Repository\Values\User\Limitation
219
     */
220
    private function createLimitation(RoleService $roleService, array $limitation)
221
    {
222
        $limitationType = $roleService->getLimitationType($limitation['identifier']);
223
224
        $limitationValue = is_array($limitation['values']) ? $limitation['values'] : array($limitation['values']);
225
226
        foreach($limitationValue as $id => $value) {
227
            $limitationValue[$id] = $this->referenceResolver->resolveReference($value);
228 1
        }
229 1
        $limitationValue = $this->limitationConverter->resolveLimitationValue($limitation['identifier'], $limitationValue);
230 1
        return $limitationType->buildValue($limitationValue);
231
    }
232
233
    /**
234
     * Assign a role to users and groups in the assignment array.
235
     *
236
     * <pre>
237
     * $assignments = array(
238
     *      array(
239
     *          'type' => 'user',
240
     *          'ids' => array(user ids),
241
     *          'limitation' => array(limitations)
242
     *      )
243
     * )
244
     * </pre>
245
     *
246
     * @param \eZ\Publish\API\Repository\Values\User\Role $role
247
     * @param \eZ\Publish\API\Repository\RoleService $roleService
248
     * @param \eZ\Publish\API\Repository\UserService $userService
249
     * @param array $assignments
250
     */
251
    private function assignRole(Role $role, RoleService $roleService, UserService $userService, array $assignments)
252
    {
253
        foreach ($assignments as $assign) {
254
            switch ($assign['type']) {
255 View Code Duplication
                case 'user':
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...
256
                    foreach ($assign['ids'] as $userId) {
257
                        $userId = $this->referenceResolver->resolveReference($userId);
258
259
                        $user = $userService->loadUser($userId);
260
261
                        if (!isset($assign['limitations'])) {
262
                            $roleService->assignRoleToUser($role, $user);
263
                        } else {
264
                            foreach ($assign['limitations'] as $limitation) {
265
                                $limitationObject = $this->createLimitation($roleService, $limitation);
266
                                $roleService->assignRoleToUser($role, $user, $limitationObject);
0 ignored issues
show
Documentation introduced by
$limitationObject is of type object<eZ\Publish\API\Re...Values\User\Limitation>, but the function expects a null|object<eZ\Publish\A...itation\RoleLimitation>.

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...
267
                            }
268
                        }
269
                    }
270
                    break;
271 View Code Duplication
                case 'group':
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...
272
                    foreach ($assign['ids'] as $groupId) {
273
                        $groupId = $this->referenceResolver->resolveReference($groupId);
274
275
                        $group = $userService->loadUserGroup($groupId);
276
277
                        if (!isset($assign['limitations'])) {
278
                            // q: why are we swallowing exceptions here ?
279 1
                            //try {
280
                                $roleService->assignRoleToUserGroup($role, $group);
281 1
                            //} catch (InvalidArgumentException $e) {}
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
282
                        } else {
283 1
                            foreach ($assign['limitations'] as $limitation) {
284
                                $limitationObject = $this->createLimitation($roleService, $limitation);
285
                                // q: why are we swallowing exceptions here ?
286
                                //try {
287
                                    $roleService->assignRoleToUserGroup($role, $group, $limitationObject);
0 ignored issues
show
Documentation introduced by
$limitationObject is of type object<eZ\Publish\API\Re...Values\User\Limitation>, but the function expects a null|object<eZ\Publish\A...itation\RoleLimitation>.

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...
288
                                //} catch (InvalidArgumentException $e) {}
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
289
                            }
290 1
                        }
291 1
                    }
292
                    break;
293
            }
294
        }
295
    }
296
297
    /**
298
     * Add new policies to the $role Role.
299
     *
300
     * @param \eZ\Publish\API\Repository\Values\User\Role $role
301
     * @param \eZ\Publish\API\Repository\RoleService $roleService
302
     * @param array $policy
303
     */
304
    private function addPolicy(Role $role, RoleService $roleService, array $policy)
305
    {
306
        $policyCreateStruct = $roleService->newPolicyCreateStruct($policy['module'], $policy['function']);
307
308
        if (array_key_exists('limitations', $policy)) {
309
            foreach ($policy['limitations'] as $limitation) {
310
                $limitationObject = $this->createLimitation($roleService, $limitation);
311
                $policyCreateStruct->addLimitation($limitationObject);
312
            }
313
        }
314
315
        $roleService->addPolicy($role, $policyCreateStruct);
316
    }
317
318
    /**
319
     * @param string $identifier
320
     * @param string $mode
321
     * @throws \Exception
322
     * @return array
323
     */
324
    public function generateMigration($identifier, $mode)
325
    {
326
        $this->loginUser(self::ADMIN_USER_ID);
327
328
        /** @var \eZ\Publish\API\Repository\Values\User\Role $role */
329
        $role = $this->roleMatcher->matchOneByKey($identifier);
330
331
        $policies = array();
332
        /** @var \eZ\Publish\API\Repository\Values\User\Policy $policy */
333
        foreach ($role->getPolicies() as $policy) {
334
            $limitations = array();
335
336
            /** @var \eZ\Publish\API\Repository\Values\User\Limitation $limitation */
337
            foreach ($policy->getLimitations() as $limitation) {
338
                $limitations[] = $this->limitationConverter->getLimitationArrayWithIdentifiers($limitation);
339
            }
340
341
            $policies[] = array(
342
                'module' => $policy->module,
343
                'function' => $policy->function,
344
                'limitations' => $limitations
345
            );
346
        }
347
348
        $data = array(
349
            'type' => 'role',
350
            'mode' => $mode
351
        );
352
353
        switch ($mode) {
354
            case 'create':
355
                $data = array_merge(
356
                    $data,
357
                    array(
358
                        'name' => $identifier
359
                    )
360
                );
361
                break;
362
            case 'update':
363
                $data = array_merge(
364
                    $data,
365
                    array(
366
                        'match' => array(
367
                            'identifier' => $identifier
368
                        )
369
                    )
370
                );
371
                break;
372
            default:
373
                throw new \Exception("Executor 'content_type' doesn't support mode '$mode'");
374
        }
375
376
        $data = array_merge(
377
            $data,
378
            array(
379
                'policies' => $policies
380
            )
381
        );
382
383
        return array($data);
384
    }
385
}
386