Completed
Pull Request — master (#91)
by
unknown
06:19
created

UserManager::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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