Completed
Push — master ( 751bcb...cbbd52 )
by Gaetano
08:11
created

UserManager   B

Complexity

Total Complexity 45

Size/Duplication

Total Lines 240
Duplicated Lines 21.67 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 81.1%

Importance

Changes 0
Metric Value
wmc 45
lcom 1
cbo 10
dl 52
loc 240
ccs 103
cts 127
cp 0.811
rs 8.3673
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
C update() 3 72 17
A delete() 0 12 2
B create() 12 44 4
C matchUsers() 0 29 11
D setReferences() 37 37 10

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like UserManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use UserManager, and based on these observations, apply Extract Interface, too.

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